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

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

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

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

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

No files matched your search

@@ -0,0 +1,127 @@
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Bmff;
using Chronos.Core.Model;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
public sealed class BmffTests
{
[Test]
public void Cr3()
{
var m = Read(Fixtures.Cr3(), "IMG_0001.CR3");
AssertNoFault(m);
Assert.Empty(m.Warnings);
Assert.Equal(ImageFileFormat.Cr3, m.Format);
Assert.Equal("Canon", m.Make);
Assert.Equal("Canon EOS R5", m.Model);
Assert.Equal(8, m.Orientation);
Assert.Equal((8352, 5586), (m.Width, m.Height));
Assert.Equal(14, m.BitsPerSample);
AssertPreviews(m, (8192, 5464, PreviewKind.FullSize), (1620, 1080, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail));
Assert.Equal(new DateTime(2024, 6, 1, 8, 0, 0, 500), m.CapturedAt);
Assert.Equal(-240, m.UtcOffsetMinutes);
Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource);
Assert.Approximately(0.01, m.ExposureTime!.Value, 1e-12);
Assert.Approximately(4, m.FNumber!.Value, 1e-12);
Assert.Equal(100, m.Iso);
Assert.Equal("0000098765", m.BodySerial);
Assert.Equal("RF24-105mm F4 L IS USM", m.LensModel);
Assert.Approximately(-9.26, m.Gps!.Longitude, 1e-9);
}
[Test]
public void Cr3FullSizeJpegIsTrackOneSample()
{
var bytes = Fixtures.Cr3(out var mdatStart);
var full = Read(bytes).Previews[0];
Assert.Equal(mdatStart + 8L, full.Offset);
Assert.Equal(0xFF, bytes[full.Offset]);
Assert.Equal(0xD9, bytes[full.Offset + full.Length - 1]);
}
[Theory]
[Case(false, false, 6, Name = "no transforms: Exif orientation applies")]
[Case(true, false, 8, Name = "irot 90° anticlockwise")]
[Case(true, true, 7, Name = "irot then imir left-right")]
[Case(false, true, 2, Name = "imir left-right only")]
public void HeifTransformsOverrideExifOrientation(bool rotate, bool mirror, int expected) =>
Assert.Equal(expected, Read(Fixtures.Heic(rotate, mirror), "IMG_0001.HEIC").Orientation);
[Test]
public void Heic()
{
var m = Read(Fixtures.Heic(), "IMG_0001.HEIC");
AssertNoFault(m);
Assert.Empty(m.Warnings);
Assert.Equal(ImageFileFormat.Heif, m.Format);
Assert.Equal((4032, 3024), (m.Width, m.Height));
Assert.Equal(10, m.BitsPerSample);
Assert.Equal(Fixtures.Make, m.Make);
Assert.Equal(Fixtures.Captured, m.CapturedAt);
Assert.Equal(400, m.Iso);
Assert.Equal(4, m.Rating);
Assert.Equal("Red", m.Label);
AssertPreviews(m, (160, 120, PreviewKind.Thumbnail));
}
[Test]
public void Avif()
{
var m = Read(Fixtures.Heic(major: "avif"), "a.avif");
Assert.Equal(ImageFileFormat.Avif, m.Format);
Assert.Equal((4032, 3024), (m.Width, m.Height));
Assert.Equal("Red", m.Label);
}
[Test]
public void WalksLargeSizeToEndAndUuidBoxes()
{
var guid = Guid.NewGuid();
byte[] large = [.. Box.U32(1), .. Box.Ascii("free"), .. Box.U64(20), 1, 2, 3, 4];
byte[] data = [.. Box.Make("ftyp", Box.Ascii("heic")), .. large, .. Box.Uuid(guid, [9, 9]), .. Box.U32(0), .. Box.Ascii("mdat"), 7, 7, 7];
var boxes = BmffReader.ReadChildren(new MemoryStream(data), 0, data.Length);
Assert.Equal(4, boxes.Count);
Assert.True(boxes[1].Is("free"));
Assert.Equal(16, boxes[1].HeaderSize);
Assert.Equal(20L, boxes[1].Size);
Assert.Equal(guid, boxes[2].UserType);
Assert.Equal(24, boxes[2].HeaderSize);
Assert.True(boxes[3].Is("mdat"));
Assert.Equal((long)data.Length, boxes[3].End);
}
[Test]
public void StopsAtMalformedAndClampsTruncatedBoxes()
{
var warnings = new List<string>();
byte[] truncated = [.. Box.Make("ftyp", Box.Ascii("heic")), .. Box.U32(1000), .. Box.Ascii("moov"), 0, 0];
var boxes = BmffReader.ReadChildren(new MemoryStream(truncated), 0, truncated.Length, warnings);
Assert.Equal(2, boxes.Count);
Assert.Equal((long)truncated.Length, boxes[1].End);
Assert.Contains("Box 'moov' at 12 runs past its container", warnings);
byte[] malformed = [.. Box.Make("ftyp", Box.Ascii("heic")), .. Box.U32(4), .. Box.Ascii("bad!"), .. Box.Make("free")];
Assert.Equal(1, BmffReader.ReadChildren(new MemoryStream(malformed), 0, malformed.Length).Count);
}
[Test]
public void FindPathIsDepthLimited()
{
var box = new BmffBox(FourCC.From("moov"), 0, 8, 8, Guid.Empty);
Assert.Throws<ArgumentException>(() => BmffReader.FindPath(new MemoryStream(new byte[8]), box, [.. Enumerable.Repeat("trak", BmffReader.MaxDepth + 1)]));
Assert.Null(BmffReader.FindPath(new MemoryStream(new byte[8]), box, "trak", "mdia"));
}
[Test]
public void FourCCRoundTrips()
{
Assert.Equal(0x66747970u, FourCC.From("ftyp"));
Assert.Equal("ftyp", FourCC.Format(0x66747970));
Assert.Equal("?abc", FourCC.Format(0x01616263));
}
}
@@ -0,0 +1,68 @@
using System.Buffers.Binary;
using System.Text;
namespace Chronos.Core.Tests.Metadata.Builders;
/// <summary>ISO-BMFF / RIFF / PNG byte helpers for synthetic containers.</summary>
internal static class Box
{
public static byte[] Make(string type, params byte[][] content)
{
var size = 8 + content.Sum(c => c.Length);
return [.. U32((uint)size), .. Encoding.Latin1.GetBytes(type), .. content.SelectMany(c => c)];
}
public static byte[] Full(string type, byte version, uint flags, params byte[][] content) =>
Make(type, [[version, (byte)(flags >> 16), (byte)(flags >> 8), (byte)flags], .. content]);
public static byte[] Uuid(Guid userType, params byte[][] content) =>
Make("uuid", [userType.ToByteArray(bigEndian: true), .. content]);
public static byte[] U8(byte v) => [v];
public static byte[] U16(ushort v)
{
var b = new byte[2];
BinaryPrimitives.WriteUInt16BigEndian(b, v);
return b;
}
public static byte[] U32(uint v)
{
var b = new byte[4];
BinaryPrimitives.WriteUInt32BigEndian(b, v);
return b;
}
public static byte[] U64(ulong v)
{
var b = new byte[8];
BinaryPrimitives.WriteUInt64BigEndian(b, v);
return b;
}
public static byte[] Ascii(string s) => Encoding.Latin1.GetBytes(s);
public static byte[] Zeros(int n) => new byte[n];
/// <summary>RIFF chunk: FourCC, little-endian size, data, pad byte to even length.</summary>
public static byte[] Riff(string fourCC, byte[] data)
{
var b = new byte[8 + data.Length + (data.Length & 1)];
Encoding.Latin1.GetBytes(fourCC).CopyTo(b, 0);
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), (uint)data.Length);
data.CopyTo(b, 8);
return b;
}
/// <summary>PNG chunk with a real CRC.</summary>
public static byte[] Png(string type, byte[] data)
{
var b = new byte[12 + data.Length];
BinaryPrimitives.WriteUInt32BigEndian(b, (uint)data.Length);
Encoding.Latin1.GetBytes(type).CopyTo(b, 4);
data.CopyTo(b, 8);
BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(8 + data.Length), Core.Hashing.Crc32.Compute(b.AsSpan(4, 4 + data.Length)));
return b;
}
}
@@ -0,0 +1,417 @@
using System.Buffers.Binary;
using System.Text;
using Chronos.Core.Metadata.Tiff;
namespace Chronos.Core.Tests.Metadata.Builders;
/// <summary>Synthetic files for every container Chronos reads. The canonical camera values below are what the tests
/// expect back; each RAW-like fixture also exercises its vendor MakerNote and preview layout.</summary>
internal static class Fixtures
{
public const string Make = "TestCam";
public const string Model = "TC-1";
public const string Xmp = """
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="4">
<xmp:Label>Red</xmp:Label>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
""";
public static readonly Guid CanonUuid = new("85c0b687-820f-11e0-8111-f4ce462b6a48");
public static readonly Guid PreviewUuid = new("eaf42b5e-1c98-4b88-b9fb-b7dc406e4d16");
/// <summary>12:34:56.123 +02:00 on 2024-05-01.</summary>
public static readonly DateTime Captured = new DateTime(2024, 5, 1, 12, 34, 56, DateTimeKind.Unspecified).AddTicks(1_230_000);
public static IfdSpec Ifd0(string make = Make, string model = Model, ushort orientation = 6) => new IfdSpec()
.Ascii(TiffTags.Make, make)
.Ascii(TiffTags.Model, model)
.Short(TiffTags.Orientation, orientation)
.Ascii(TiffTags.Software, "fw 1.0")
.Ascii(TiffTags.Artist, "Ada")
.Ascii(TiffTags.Copyright, "(c) Ada")
.Short(TiffTags.Rating, 3);
/// <summary>Every standard Exif field Chronos reads; <paramref name="identity"/> adds body serial and lens model.</summary>
public static IfdSpec ExifIfd(bool identity = true, ushort iso = 400)
{
var exif = new IfdSpec()
.Rational(TiffTags.ExposureTime, (1, 250))
.Rational(TiffTags.FNumber, (56, 10))
.Ascii(TiffTags.DateTimeOriginal, "2024:05:01 12:34:56")
.Ascii(TiffTags.SubSecTimeOriginal, "123")
.Ascii(TiffTags.OffsetTimeOriginal, "+02:00")
.Ascii(TiffTags.DateTimeDigitized, "2024:05:01 12:34:57")
.Rational(TiffTags.FocalLength, (35, 1))
.Short(TiffTags.FocalLengthIn35mmFilm, 52)
.SRational(TiffTags.ExposureBiasValue, -2, 3)
.Short(TiffTags.ExposureProgram, 3)
.Short(TiffTags.MeteringMode, 5)
.Short(TiffTags.WhiteBalance, 1)
.Short(TiffTags.Flash, 16)
.Long(TiffTags.PixelXDimension, 4000)
.Long(TiffTags.PixelYDimension, 3000);
if (iso > 0) exif.Short(TiffTags.IsoSpeedRatings, iso);
if (identity) exif.Ascii(TiffTags.BodySerialNumber, "SN123").Ascii(TiffTags.LensModel, "TestLens 35mm");
return exif;
}
/// <summary>45.5° N, 9.26° W, 120.5 m, 2024-05-01 10:34:56 UTC.</summary>
public static IfdSpec GpsIfd() => new IfdSpec()
.Bytes(TiffTags.GpsVersionId, 2, 3, 0, 0)
.Ascii(TiffTags.GpsLatitudeRef, "N")
.Rational(TiffTags.GpsLatitude, (45, 1), (30, 1), (0, 1))
.Ascii(TiffTags.GpsLongitudeRef, "W")
.Rational(TiffTags.GpsLongitude, (9, 1), (15, 1), (3600, 100))
.Bytes(TiffTags.GpsAltitudeRef, 0)
.Rational(TiffTags.GpsAltitude, (1205, 10))
.Rational(TiffTags.GpsTimeStamp, (10, 1), (34, 1), (56, 1))
.Ascii(TiffTags.GpsDateStamp, "2024:05:01");
/// <summary>Canonical Exif TIFF block; IFD1 carries a 160×120 JPEG thumbnail.</summary>
public static byte[] ExifTiff(bool littleEndian = true, IfdSpec? exif = null, IfdSpec? ifd0 = null)
{
var root = (ifd0 ?? Ifd0()).Child(TiffTags.ExifIfd, exif ?? ExifIfd()).Child(TiffTags.GpsIfd, GpsIfd());
root.Next = new IfdSpec()
.Short(TiffTags.Compression, 6)
.Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(160, 120));
return TiffFile.Build(root, littleEndian);
}
/// <summary>4000×3000 JPEG: Exif (+thumbnail), XMP, MPF with a 1920×1440 large thumbnail and a disparity image
/// (not a preview).</summary>
public static byte[] Jpeg(bool littleEndian = true) => new JpegBuilder()
.Segment(0xE0, [.. "JFIF\0"u8, 1, 2, 0, 0, 1, 0, 1, 0, 0])
.Exif(ExifTiff(littleEndian))
.Xmp(Xmp)
.Mpf((JpegBuilder.Minimal(1920, 1440), 0x00010002), (JpegBuilder.Minimal(640, 480), 0x00020002))
.Build(4000, 3000);
/// <summary>CR2: "CR" marker, IFD0 full-size JPEG strip (6720×4480), IFD1 thumbnail, IFD2 RGB, IFD3 lossless
/// raw (SOF3, 14-bit); Canon MakerNote supplies serial, lens, IS and colour temperature.</summary>
public static byte[] Cr2()
{
var makerNote = new IfdSpec()
.Short(0x0001, [.. Enumerable.Range(0, 40).Select(i => (ushort)(i == 34 ? 1 : 0))])
.Long(0x000C, 123456)
.Long(0x0010, 0x80000349)
.Ascii(0x0095, "EF24-70mm f/2.8L II USM")
.Short(0x00AE, 5200);
var exif = ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true);
var ifd0 = Ifd0("Canon", "Canon EOS 5D Mark IV", 1)
.Long(TiffTags.ImageWidth, 6720).Long(TiffTags.ImageLength, 4480)
.Short(TiffTags.BitsPerSample, 8, 8, 8)
.Short(TiffTags.Compression, 6)
.Strip(JpegBuilder.Minimal(6720, 4480))
.Child(TiffTags.ExifIfd, exif);
var ifd1 = new IfdSpec().Short(TiffTags.Compression, 6)
.Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(160, 120));
var ifd2 = new IfdSpec().Long(TiffTags.ImageWidth, 592).Long(TiffTags.ImageLength, 395)
.Short(TiffTags.BitsPerSample, 16, 16, 16).Short(TiffTags.Compression, 1).Strip(new byte[64]);
var ifd3 = new IfdSpec().Short(TiffTags.Compression, 6).Strip(JpegBuilder.Minimal(2784, 3708, 0xC3, 14));
ifd0.Next = ifd1;
ifd1.Next = ifd2;
ifd2.Next = ifd3;
return TiffFile.Build(ifd0, true, headerExtra: [(byte)'C', (byte)'R', 2, 0, 0, 0, 0, 0]);
}
/// <summary>Big-endian NEF: IFD0 RGB thumbnail; SubIFDs JpgFromRaw (8256×5504) and 14-bit CFA raw (8288×5520);
/// Nikon type-3 MakerNote (serial, shutter count, lens, VR, ISO used because Exif ISO is absent).</summary>
public static byte[] Nef()
{
var nikon = new IfdSpec()
.Short(0x0002, 0, 64)
.Ascii(0x001D, "3001234")
.Undefined(0x001F, [.. "0100"u8, 1, 0, 0, 0])
.Rational(0x0084, (24, 1), (70, 1), (28, 10), (28, 10))
.Long(0x00A7, 12345);
var exif = ExifIfd(identity: false, iso: 0)
.Undefined(TiffTags.MakerNote, [.. "Nikon\0"u8, 2, 0x11, 0, 0, .. TiffFile.Build(nikon, littleEndian: false)]);
var jpgFromRaw = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Short(TiffTags.Compression, 6)
.Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(8256, 5504));
var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0)
.Long(TiffTags.ImageWidth, 8288).Long(TiffTags.ImageLength, 5520)
.Short(TiffTags.BitsPerSample, 14).Short(TiffTags.Compression, 34713)
.Short(TiffTags.PhotometricInterpretation, 32803).Strip(new byte[128]);
var ifd0 = Ifd0("NIKON CORPORATION", "NIKON D850", 1)
.Long(TiffTags.NewSubfileType, 1)
.Long(TiffTags.ImageWidth, 160).Long(TiffTags.ImageLength, 120)
.Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 1).Strip(new byte[96])
.Child(TiffTags.SubIfds, jpgFromRaw, raw)
.Child(TiffTags.ExifIfd, exif);
return TiffFile.Build(ifd0, littleEndian: false);
}
/// <summary>DNG: IFD0 thumbnail with CameraSerialNumber; SubIFDs 16-bit CFA raw (4032×3024, lossless JPEG strip,
/// excluded as CFA) and a 1024×768 YCbCr JPEG preview (NewSubfileType 1).</summary>
public static byte[] Dng()
{
var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0)
.Long(TiffTags.ImageWidth, 4032).Long(TiffTags.ImageLength, 3024)
.Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 7)
.Short(TiffTags.PhotometricInterpretation, 32803).Strip(JpegBuilder.Minimal(2016, 3024, 0xC3, 12));
var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1)
.Long(TiffTags.ImageWidth, 1024).Long(TiffTags.ImageLength, 768)
.Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 7)
.Short(TiffTags.PhotometricInterpretation, 6).Strip(JpegBuilder.Minimal(1024, 768));
var ifd0 = Ifd0("Google", "Pixel 8", 1)
.Long(TiffTags.NewSubfileType, 1)
.Long(TiffTags.ImageWidth, 256).Long(TiffTags.ImageLength, 192)
.Short(TiffTags.BitsPerSample, 8, 8, 8).Short(TiffTags.Compression, 1).Short(TiffTags.PhotometricInterpretation, 2)
.Strip(new byte[48])
.Bytes(TiffTags.DngVersion, 1, 4, 0, 0)
.Ascii(TiffTags.CameraSerialNumber, "DNGSER1")
.Child(TiffTags.SubIfds, raw, preview)
.Child(TiffTags.ExifIfd, ExifIfd(identity: false));
return TiffFile.Build(ifd0);
}
/// <summary>ARW: IFD0 is a 1616×1080 JPEG preview, SubIFD the 12-bit raw; "SONY DSC" MakerNote with LensSpec.</summary>
public static byte[] Arw()
{
var sony = new IfdSpec()
.Long(0xB021, 5600)
.Long(0xB026, 1)
.Undefined(0xB02A, [0x00, 0x00, 0x24, 0x00, 0x70, 0x28, 0x28, 0x00]);
var exif = ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "SONY DSC \0\0\0"u8], sony, relativeToTiff: true, littleEndian: true);
var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0)
.Long(TiffTags.ImageWidth, 6048).Long(TiffTags.ImageLength, 4024)
.Short(TiffTags.BitsPerSample, 12).Short(TiffTags.Compression, 32767)
.Short(TiffTags.PhotometricInterpretation, 32803).Strip(new byte[64]);
var ifd0 = Ifd0("SONY", "ILCE-7M3", 1)
.Long(TiffTags.NewSubfileType, 1).Short(TiffTags.Compression, 6)
.Blob(TiffTags.JpegInterchangeFormat, TiffTags.JpegInterchangeFormatLength, JpegBuilder.Minimal(1616, 1080))
.Child(TiffTags.SubIfds, raw)
.Child(TiffTags.ExifIfd, exif);
return TiffFile.Build(ifd0);
}
/// <summary>ORF ("IIRO"): raw in IFD0; "OM SYSTEM" MakerNote with Equipment (serial, lens) and CameraSettings
/// (3200×2400 preview at a MakerNote-relative offset, IS on).</summary>
public static byte[] Orf()
{
var equipment = new IfdSpec().Ascii(0x0101, "BHX123").Ascii(0x0203, "M.Zuiko 12-40mm F2.8");
var settings = new IfdSpec().Long(0x0100, 1).Blob(0x0101, 0x0102, JpegBuilder.Minimal(3200, 2400)).Long(0x0604, 1);
var olympus = new IfdSpec().Child(0x2010, equipment).Child(0x2020, settings);
var exif = ExifIfd(identity: false)
.Embedded(TiffTags.MakerNote, [.. "OM SYSTEM\0\0\0II"u8, 4, 0], olympus, relativeToTiff: false, littleEndian: true);
var ifd0 = Ifd0("OM Digital Solutions", "OM-1", 1)
.Long(TiffTags.ImageWidth, 5240).Long(TiffTags.ImageLength, 3912)
.Short(TiffTags.BitsPerSample, 12).Short(TiffTags.Compression, 1).Strip(new byte[64])
.Child(TiffTags.ExifIfd, exif);
return TiffFile.Build(ifd0, magic: "IIRO");
}
/// <summary>RW2 ("IIU\0"): sensor borders give 5776×4344, 12-bit, ISO 800; JpgFromRaw (1920×1440) carries the Exif
/// block with a Panasonic MakerNote (internal serial, lens type, IS, colour temperature).</summary>
public static byte[] Rw2()
{
var panasonic = new IfdSpec()
.Short(0x001A, 2)
.Undefined(0x0025, [.. "F541504040123"u8, 0, 0, 0])
.Short(0x0044, 5000)
.Ascii(0x0051, "LUMIX G VARIO 12-60mm");
var exif = ExifIfd(identity: false, iso: 800)
.Embedded(TiffTags.MakerNote, [.. "Panasonic\0\0\0"u8], panasonic, relativeToTiff: true, littleEndian: true);
var jpeg = new JpegBuilder().Exif(ExifTiff(true, exif, Ifd0("Panasonic", "DC-GH6", 1))).Build(1920, 1440);
var ifd0 = new IfdSpec()
.Short(0x0002, 5800).Short(0x0003, 4360)
.Short(0x0004, 8).Short(0x0005, 12).Short(0x0006, 4352).Short(0x0007, 5788)
.Short(0x000A, 12).Short(0x0017, 800)
.Undefined(0x002E, jpeg)
.Ascii(TiffTags.Make, "Panasonic").Ascii(TiffTags.Model, "DC-GH6").Short(TiffTags.Orientation, 1);
return TiffFile.Build(ifd0, magic: "IIU\0");
}
/// <summary>CR3: CMT1–4 + THMB in the Canon uuid, PRVW in the preview uuid, track 1 full-size JPEG (8192×5464),
/// track 2 raw with CMP1 (8352×5586, 14-bit); <c>mdat</c> comes last.</summary>
public static byte[] Cr3() => Cr3(out _);
public static byte[] Cr3(out int mdatStart)
{
var full = JpegBuilder.Minimal(8192, 5464);
var canonMakerNote = TiffFile.Build(new IfdSpec().Long(0x000C, 98765).Ascii(0x0095, "RF24-105mm F4 L IS USM"));
var cmt2 = new IfdSpec()
.Rational(TiffTags.ExposureTime, (1, 100)).Rational(TiffTags.FNumber, (4, 1)).Short(TiffTags.IsoSpeedRatings, 100)
.Ascii(TiffTags.DateTimeOriginal, "2024:06:01 08:00:00").Ascii(TiffTags.SubSecTimeOriginal, "50")
.Ascii(TiffTags.OffsetTimeOriginal, "-04:00");
var thumb = JpegBuilder.Minimal(160, 120);
var canon = Box.Uuid(CanonUuid,
Box.Make("CNCV", Box.Ascii("CanonCR3_001/00.09.00/00.00.00")),
Box.Make("CMT1", TiffFile.Build(Ifd0("Canon", "Canon EOS R5", 8).Long(TiffTags.ImageWidth, 8192).Long(TiffTags.ImageLength, 5464))),
Box.Make("CMT2", TiffFile.Build(cmt2)),
Box.Make("CMT3", canonMakerNote),
Box.Make("CMT4", TiffFile.Build(GpsIfd())),
Box.Make("THMB", [0, 0, 0, 0], Box.U16(160), Box.U16(120), Box.U32((uint)thumb.Length), Box.U16(0xFF), Box.U16(0xFF), thumb));
var prvwJpeg = JpegBuilder.Minimal(1620, 1080);
var preview = Box.Uuid(PreviewUuid, Box.U64(0),
Box.Make("PRVW", Box.U32(0), Box.U16(1), Box.U16(1620), Box.U16(1080), Box.U16(1), Box.U32((uint)prvwJpeg.Length), prvwJpeg));
byte[] Build(uint jpegOffset)
{
var moov = Box.Make("moov", canon, Box.Make("mvhd", Box.Zeros(100)),
Track(Box.Make("JPEG", Box.Zeros(4)), Box.U32(0), Box.U32(1), Box.U32((uint)full.Length), jpegOffset, 8192, 5464),
Track(Box.Make("CMP1", Box.U16(0), Box.U16(0x30), Box.U32(0x100), Box.U32(8352), Box.U32(5586), Box.U32(512), Box.U32(512), [14, 0x11, 0, 0]),
Box.U32(0), Box.U32(1), Box.U32(1000), jpegOffset + (uint)full.Length, 8352, 5586));
return [.. Box.Make("ftyp", Box.Ascii("crx "), Box.U32(1), Box.Ascii("crx isom")), .. moov, .. preview];
}
var head = Build(0);
var offset = (uint)(head.Length + 8);
head = Build(offset);
mdatStart = head.Length;
var mdat = new byte[8 + full.Length + 1000];
BinaryPrimitives.WriteUInt32BigEndian(mdat, (uint)mdat.Length);
"mdat"u8.CopyTo(mdat.AsSpan(4));
full.CopyTo(mdat, 8);
return [.. head, .. mdat];
static byte[] Track(byte[] entryChild, byte[] sampleSize, byte[] sampleCount, byte[] firstSize, uint chunkOffset, ushort width, ushort height)
{
var craw = Box.Make("CRAW", Box.Zeros(6), Box.U16(1), Box.Zeros(16), Box.U16(width), Box.U16(height),
Box.U32(0x00480000), Box.U32(0x00480000), Box.U32(0), Box.U16(1), Box.Zeros(32), Box.U16(24), Box.U16(0xFFFF), entryChild);
var stbl = Box.Make("stbl",
Box.Full("stsd", 0, 0, Box.U32(1), craw),
Box.Full("stsz", 0, 0, sampleSize, sampleCount, firstSize),
Box.Full("stco", 0, 0, Box.U32(1), Box.U32(chunkOffset)));
return Box.Make("trak", Box.Make("mdia", Box.Make("minf", stbl)));
}
}
/// <summary>HEIC: primary hvc1 item 4032×3024 (ispe), 10-bit pixi, irot 1 (+ imir axis 1 when <paramref name="mirror"/>),
/// Exif item (orientation 6, ignored when transforms exist) and a two-extent XMP item.</summary>
public static byte[] Heic(bool rotate = true, bool mirror = false, string major = "heic")
{
var exifPayload = (byte[])[.. Box.U32(6), .. "Exif\0\0"u8, .. ExifTiff()];
var xmp = Encoding.UTF8.GetBytes(Xmp);
var split = xmp.Length / 2;
var codec = major == "avif" ? "av01" : "hvc1";
byte[] Build(uint mdatData)
{
var exifAt = mdatData + 64;
var xmpAt = exifAt + (uint)exifPayload.Length;
var properties = new List<byte[]> { Box.Full("ispe", 0, 0, Box.U32(4032), Box.U32(3024)), Box.Full("pixi", 0, 0, [3, 10, 10, 10]) };
if (rotate) properties.Add(Box.Make("irot", [1]));
if (mirror) properties.Add(Box.Make("imir", [1]));
var associations = Enumerable.Range(1, properties.Count).Select(i => (byte)(0x80 | i)).ToArray();
var meta = Box.Full("meta", 0, 0,
Box.Full("hdlr", 0, 0, Box.U32(0), Box.Ascii("pict"), Box.Zeros(12), [0]),
Box.Full("pitm", 0, 0, Box.U16(1)),
Box.Full("iinf", 0, 0, Box.U16(3),
Box.Full("infe", 2, 0, Box.U16(1), Box.U16(0), Box.Ascii(codec), [0]),
Box.Full("infe", 2, 0, Box.U16(2), Box.U16(0), Box.Ascii("Exif"), [0]),
Box.Full("infe", 2, 0, Box.U16(3), Box.U16(0), Box.Ascii("mime"), [0], Box.Ascii("application/rdf+xml"), [0])),
Box.Full("iloc", 1, 0, [0x44, 0x00], Box.U16(3),
Box.U16(1), Box.U16(0), Box.U16(0), Box.U16(1), Box.U32(mdatData), Box.U32(64),
Box.U16(2), Box.U16(0), Box.U16(0), Box.U16(1), Box.U32(exifAt), Box.U32((uint)exifPayload.Length),
Box.U16(3), Box.U16(0), Box.U16(0), Box.U16(2), Box.U32(xmpAt), Box.U32((uint)split), Box.U32(xmpAt + (uint)split), Box.U32((uint)(xmp.Length - split))),
Box.Make("iprp",
Box.Make("ipco", [.. properties.SelectMany(p => p)]),
Box.Full("ipma", 0, 0, Box.U32(1), Box.U16(1), [(byte)associations.Length], associations)));
return [.. Box.Make("ftyp", Box.Ascii(major), Box.U32(0), Box.Ascii("mif1"), Box.Ascii(major)), .. meta];
}
var head = Build(0);
var data = (uint)(head.Length + 8);
head = Build(data);
return [.. head, .. Box.Make("mdat", Box.Zeros(64), exifPayload, xmp)];
}
/// <summary>RAF: big-endian directory; embedded 1920×1280 JPEG with Exif and a Fujifilm MakerNote; RAF records give
/// 7752×5178 (cropped) and the FujiIFD 14-bit.</summary>
public static byte[] Raf()
{
var fuji = new IfdSpec().Ascii(0x0010, "FF02B1234567").Short(0x1005, 6100).Short(0x1422, 2, 1, 0);
var exif = ExifIfd(identity: false)
.Embedded(TiffTags.MakerNote, [.. "FUJIFILM"u8, 12, 0, 0, 0], fuji, relativeToTiff: false, littleEndian: true);
var jpeg = new JpegBuilder().Exif(ExifTiff(true, exif, Ifd0("FUJIFILM", "X-T5", 1))).Build(1920, 1280);
var records = (byte[])[.. Box.U32(2), .. Box.U16(0x0100), .. Box.U16(4), .. Box.U16(5280), .. Box.U16(7920),
.. Box.U16(0x0111), .. Box.U16(4), .. Box.U16(5178), .. Box.U16(7752)];
var fujiIfd = TiffFile.Build(new IfdSpec().Child(0xF000, new IfdSpec().Long(0xF001, 7920).Long(0xF002, 5280).Long(0xF003, 14)), littleEndian: false);
var jpegOffset = 0x6C;
var recordsOffset = jpegOffset + jpeg.Length;
var cfaOffset = recordsOffset + records.Length;
var header = new byte[0x6C];
"FUJIFILMCCD-RAW 0201FF129502"u8.CopyTo(header);
"X-T5"u8.CopyTo(header.AsSpan(0x1C));
"0100"u8.CopyTo(header.AsSpan(0x3C));
uint[] directory = [(uint)jpegOffset, (uint)jpeg.Length, (uint)recordsOffset, (uint)records.Length, (uint)cfaOffset, (uint)fujiIfd.Length];
for (var i = 0; i < directory.Length; i++) BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(0x54 + 4 * i), directory[i]);
return [.. header, .. jpeg, .. records, .. fujiIfd];
}
/// <summary>WebP with VP8X canvas 3000×2000, a VP8L bitstream, EXIF (no prefix) and XMP chunks.</summary>
public static byte[] WebP()
{
byte[] vp8x = [0x0C, 0, 0, 0, .. UInt24(2999), .. UInt24(1999)];
var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8X", vp8x), .. Box.Riff("VP8L", Vp8L(3000, 2000)),
.. Box.Riff("EXIF", ExifTiff(false)), .. Box.Riff("XMP ", Encoding.UTF8.GetBytes(Xmp))];
return [.. "RIFF"u8, .. LittleEndian32(body.Length), .. body];
}
/// <summary>Simple lossy WebP (VP8 key frame) without metadata.</summary>
public static byte[] WebPLossy(int width, int height)
{
byte[] frame = [0x10, 0x02, 0x00, 0x9D, 0x01, 0x2A, (byte)width, (byte)(width >> 8), (byte)height, (byte)(height >> 8), 0, 0];
var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8 ", frame)];
return [.. "RIFF"u8, .. LittleEndian32(body.Length), .. body];
}
public static byte[] Vp8L(int width, int height)
{
var bits = (uint)(width - 1) | (uint)(height - 1) << 14;
return [0x2F, .. LittleEndian32((int)bits), 0];
}
/// <summary>PNG 2048×1536 16-bit RGB with eXIf (big-endian TIFF), iTXt XMP (zlib-compressed when asked), IDAT, IEND.</summary>
public static byte[] Png(bool compressedXmp = false)
{
var ihdr = (byte[])[.. Box.U32(2048), .. Box.U32(1536), 16, 2, 0, 0, 0];
var xmp = Encoding.UTF8.GetBytes(Xmp);
if (compressedXmp)
{
using var output = new MemoryStream();
using (var z = new System.IO.Compression.ZLibStream(output, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true)) z.Write(xmp);
xmp = output.ToArray();
}
var itxt = (byte[])[.. "XML:com.adobe.xmp\0"u8, compressedXmp ? (byte)1 : (byte)0, 0, 0, 0, .. xmp];
return [0x89, .. "PNG\r\n\u001a\n"u8, .. Box.Png("IHDR", ihdr), .. Box.Png("eXIf", ExifTiff(false)),
.. Box.Png("iTXt", itxt), .. Box.Png("IDAT", new byte[32]), .. Box.Png("IEND", [])];
}
/// <summary>Every fixture by name, for table-driven and fuzz tests.</summary>
public static byte[] ByName(string name) => name switch
{
"jpeg" => Jpeg(),
"jpeg-be" => Jpeg(false),
"cr2" => Cr2(),
"nef" => Nef(),
"dng" => Dng(),
"arw" => Arw(),
"orf" => Orf(),
"rw2" => Rw2(),
"cr3" => Cr3(),
"heic" => Heic(),
"avif" => Heic(major: "avif"),
"raf" => Raf(),
"webp" => WebP(),
"png" => Png(),
"png-z" => Png(compressedXmp: true),
_ => throw new ArgumentException(name),
};
private static byte[] UInt24(int v) => [(byte)v, (byte)(v >> 8), (byte)(v >> 16)];
private static byte[] LittleEndian32(int v)
{
var b = new byte[4];
BinaryPrimitives.WriteInt32LittleEndian(b, v);
return b;
}
}
@@ -0,0 +1,276 @@
using System.Buffers.Binary;
using System.Text;
using Chronos.Core.Metadata.Tiff;
namespace Chronos.Core.Tests.Metadata.Builders;
/// <summary>Declarative IFD for synthetic test files: typed values, child-IFD pointers, data blobs and embedded
/// (MakerNote-style) IFDs. Serialised by <see cref="TiffFile"/> in either byte order.</summary>
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<Entry> Entries { get; } = [];
/// <summary>Next IFD in the chain (IFD1 after IFD0…).</summary>
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));
/// <summary>LONG pointer(s) to child IFDs (Exif, GPS, SubIFDs, MakerNote sub-directories).</summary>
public IfdSpec Child(ushort tag, params IfdSpec[] children) => Add(new ChildrenEntry(tag, children));
/// <summary>LONG offset to <paramref name="data"/> (placed after all IFDs) plus an optional LONG length tag.</summary>
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);
/// <summary>UNDEFINED value made of <paramref name="prefix"/> and an IFD whose offsets are relative to the TIFF base
/// (<paramref name="relativeToTiff"/>) or to the start of the value itself.</summary>
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;
}
}
/// <summary>Serialises <see cref="IfdSpec"/> trees: IFDs in depth-first order, each followed by its values, blobs last.</summary>
internal static class TiffFile
{
/// <summary>A complete TIFF file/block with header (<paramref name="magic"/> overrides "II*\0"/"MM\0*", e.g. "IIRO");
/// <paramref name="headerExtra"/> follows the 8-byte header (the CR2 "CR" marker block).</summary>
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();
}
/// <summary>An IFD and its values laid out as if placed at <paramref name="origin"/> relative to the offset base.</summary>
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<byte> _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<byte> 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<byte> 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<byte> s, ushort v)
{
if (le) BinaryPrimitives.WriteUInt16LittleEndian(s, v);
else BinaryPrimitives.WriteUInt16BigEndian(s, v);
}
private void Write32(Span<byte> s, uint v)
{
if (le) BinaryPrimitives.WriteUInt32LittleEndian(s, v);
else BinaryPrimitives.WriteUInt32BigEndian(s, v);
}
}
}
@@ -0,0 +1,149 @@
using System.Buffers.Binary;
using System.Text;
namespace Chronos.Core.Tests.Metadata.Builders;
/// <summary>Synthetic JPEG: SOI, arbitrary segments/raw bytes, an optional APP2 MPF index of appended secondary
/// images, SOFn, SOS with a fake scan, EOI. No real entropy data: parsers stop at SOS.</summary>
internal sealed class JpegBuilder
{
public const string XmpSignature = "http://ns.adobe.com/xap/1.0/\0";
public const string ExtendedXmpSignature = "http://ns.adobe.com/xmp/extension/\0";
private readonly List<byte[]> _parts = [];
private readonly List<(byte[] Jpeg, uint Type)> _secondary = [];
private int _mpfPart = -1;
/// <summary>A minimal JPEG with just a frame header (used as embedded previews).</summary>
public static byte[] Minimal(int width, int height, byte sofMarker = 0xC0, int precision = 8, int scanBytes = 32) =>
new JpegBuilder().Build(width, height, sofMarker, precision, scanBytes);
public JpegBuilder Segment(byte marker, byte[] payload)
{
var s = new byte[4 + payload.Length];
s[0] = 0xFF;
s[1] = marker;
BinaryPrimitives.WriteUInt16BigEndian(s.AsSpan(2), (ushort)(payload.Length + 2));
payload.CopyTo(s, 4);
_parts.Add(s);
return this;
}
/// <summary>Bytes inserted verbatim (fill bytes, garbage).</summary>
public JpegBuilder Raw(params byte[] bytes)
{
_parts.Add(bytes);
return this;
}
public JpegBuilder Exif(byte[] tiff) => Segment(0xE1, [.. "Exif\0\0"u8, .. tiff]);
public JpegBuilder Xmp(string packet) => Segment(0xE1, [.. Encoding.ASCII.GetBytes(XmpSignature), .. Encoding.UTF8.GetBytes(packet)]);
/// <summary>Extended XMP split into <paramref name="chunk"/>-byte APP1 segments (written in reverse order to prove
/// reassembly uses offsets).</summary>
public JpegBuilder ExtendedXmp(string guid, string packet, int chunk)
{
var data = Encoding.UTF8.GetBytes(packet);
var segments = new List<byte[]>();
for (var offset = 0; offset < data.Length; offset += chunk)
{
var piece = data.AsSpan(offset, Math.Min(chunk, data.Length - offset));
var payload = new byte[ExtendedXmpSignature.Length + 32 + 8 + piece.Length];
Encoding.ASCII.GetBytes(ExtendedXmpSignature).CopyTo(payload, 0);
Encoding.ASCII.GetBytes(guid).CopyTo(payload, ExtendedXmpSignature.Length);
BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(ExtendedXmpSignature.Length + 32), (uint)data.Length);
BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(ExtendedXmpSignature.Length + 36), (uint)offset);
piece.CopyTo(payload.AsSpan(ExtendedXmpSignature.Length + 40));
segments.Add(payload);
}
segments.Reverse();
foreach (var s in segments) Segment(0xE1, s);
return this;
}
/// <summary>APP2 MPF index; each secondary JPEG is appended after the primary's EOI with the given MP type code.</summary>
public JpegBuilder Mpf(params (byte[] Jpeg, uint Type)[] secondary)
{
_secondary.AddRange(secondary);
_mpfPart = _parts.Count;
_parts.Add([]);
return this;
}
public byte[] Build(int width, int height, byte sofMarker = 0xC0, int precision = 8, int scanBytes = 32)
{
var tail = new List<byte>();
tail.AddRange(SegmentBytes(sofMarker, [(byte)precision, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1]));
tail.AddRange(SegmentBytes(0xDA, [3, 1, 0, 2, 0x11, 3, 0x11, 0, 0x3F, 0]));
for (var i = 0; i < scanBytes; i++) tail.Add((byte)(i * 37 % 255));
tail.AddRange([0xFF, 0xD9]);
if (_mpfPart >= 0) _parts[_mpfPart] = SegmentBytes(0xE2, MpfPayload(new uint[_secondary.Count], 0));
var headLength = 2 + _parts.Sum(p => p.Length);
var primaryLength = headLength + tail.Count;
if (_mpfPart >= 0)
{
var mpHeader = 2 + _parts.Take(_mpfPart).Sum(p => p.Length) + 4 + 4;
var offsets = new uint[_secondary.Count];
var at = primaryLength;
for (var i = 0; i < offsets.Length; i++)
{
offsets[i] = (uint)(at - mpHeader);
at += _secondary[i].Jpeg.Length;
}
_parts[_mpfPart] = SegmentBytes(0xE2, MpfPayload(offsets, primaryLength));
}
var file = new List<byte>(primaryLength);
file.AddRange([0xFF, 0xD8]);
foreach (var p in _parts) file.AddRange(p);
file.AddRange(tail);
foreach (var (jpeg, _) in _secondary) file.AddRange(jpeg);
return file.ToArray();
byte[] MpfPayload(uint[] offsets, int primarySize)
{
// "MPF\0", big-endian MP header, index IFD (version, count, entries), then 16-byte MP entries.
var n = offsets.Length + 1;
var b = new byte[4 + 8 + 2 + 3 * 12 + 4 + 16 * n];
var s = b.AsSpan();
"MPF\0MM\0*"u8.CopyTo(s);
BinaryPrimitives.WriteUInt32BigEndian(s[8..], 8);
var ifd = s[12..];
BinaryPrimitives.WriteUInt16BigEndian(ifd, 3);
WriteEntry(ifd[2..], 0xB000, 7, 4, BinaryPrimitives.ReadUInt32BigEndian("0100"u8));
WriteEntry(ifd[14..], 0xB001, 4, 1, (uint)n);
WriteEntry(ifd[26..], 0xB002, 7, (uint)(16 * n), 8 + 2 + 36 + 4);
var entries = s[(4 + 8 + 2 + 36 + 4)..];
BinaryPrimitives.WriteUInt32BigEndian(entries, 0x20030000);
BinaryPrimitives.WriteUInt32BigEndian(entries[4..], (uint)primarySize);
for (var i = 0; i < offsets.Length; i++)
{
var e = entries[(16 * (i + 1))..];
BinaryPrimitives.WriteUInt32BigEndian(e, _secondary[i].Type);
BinaryPrimitives.WriteUInt32BigEndian(e[4..], (uint)_secondary[i].Jpeg.Length);
BinaryPrimitives.WriteUInt32BigEndian(e[8..], offsets[i]);
}
return b;
}
}
private static void WriteEntry(Span<byte> s, ushort tag, ushort type, uint count, uint value)
{
BinaryPrimitives.WriteUInt16BigEndian(s, tag);
BinaryPrimitives.WriteUInt16BigEndian(s[2..], type);
BinaryPrimitives.WriteUInt32BigEndian(s[4..], count);
BinaryPrimitives.WriteUInt32BigEndian(s[8..], value);
}
private static byte[] SegmentBytes(byte marker, byte[] payload)
{
var s = new byte[4 + payload.Length];
s[0] = 0xFF;
s[1] = marker;
BinaryPrimitives.WriteUInt16BigEndian(s.AsSpan(2), (ushort)(payload.Length + 2));
payload.CopyTo(s, 4);
return s;
}
}
@@ -0,0 +1,86 @@
namespace Chronos.Core.Tests.Metadata.Builders;
/// <summary>Read-only seekable stream: <c>prefix</c> bytes followed by zeros up to <c>length</c>. Simulates a large
/// RAW (image data never materialised) for I/O-bound tests.</summary>
internal sealed class SparseStream(byte[] prefix, long length) : Stream
{
private long _position;
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => length;
public override long Position
{
get => _position;
set => _position = value;
}
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
public override int Read(Span<byte> buffer)
{
var n = (int)Math.Max(0, Math.Min(buffer.Length, length - _position));
for (var i = 0; i < n; i++)
{
var p = _position + i;
buffer[i] = p < prefix.Length ? prefix[p] : (byte)0;
}
_position += n;
return n;
}
public override long Seek(long offset, SeekOrigin origin) => _position = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => _position + offset,
_ => length + offset,
};
public override void Flush()
{
}
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
/// <summary>Counts the bytes returned by <see cref="Read(Span{byte})"/> of the wrapped stream.</summary>
internal sealed class CountingStream(Stream inner) : Stream
{
public long BytesRead { get; private set; }
public int ReadCalls { get; private set; }
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position
{
get => inner.Position;
set => inner.Position = value;
}
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
public override int Read(Span<byte> buffer)
{
var n = inner.Read(buffer);
BytesRead += n;
ReadCalls++;
return n;
}
public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
public override void Flush()
{
}
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
@@ -0,0 +1,278 @@
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Model;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
public sealed class ExifTests
{
[Theory]
[Case(true)]
[Case(false)]
public void ReadsEveryFieldFromJpeg(bool littleEndian)
{
var m = Read(Fixtures.Jpeg(littleEndian), "IMG_0001.JPG");
AssertNoFault(m);
Assert.Empty(m.Warnings);
Assert.Equal(ImageFileFormat.Jpeg, m.Format);
Assert.Equal(Fixtures.Make, m.Make);
Assert.Equal(Fixtures.Model, m.Model);
Assert.Equal("SN123", m.BodySerial);
Assert.Equal("TestLens 35mm", m.LensModel);
Assert.Equal("fw 1.0", m.Software);
Assert.Equal("Ada", m.Artist);
Assert.Equal("(c) Ada", m.Copyright);
Assert.Equal(Fixtures.Captured, m.CapturedAt);
Assert.Equal(DateTimeKind.Unspecified, m.CapturedAt!.Value.Kind);
Assert.Equal(120, m.UtcOffsetMinutes);
Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource);
Assert.Approximately(1 / 250.0, m.ExposureTime!.Value, 1e-12);
Assert.Approximately(5.6, m.FNumber!.Value, 1e-12);
Assert.Equal(400, m.Iso);
Assert.Approximately(35, m.FocalLength!.Value, 1e-12);
Assert.Approximately(52, m.FocalLength35!.Value, 1e-12);
Assert.Approximately(-2 / 3.0, m.ExposureBias!.Value, 1e-12);
Assert.Equal(3, m.ExposureProgram);
Assert.Equal(5, m.MeteringMode);
Assert.Equal(1, m.WhiteBalanceMode);
Assert.Equal(16, m.Flash);
Assert.Null(m.ColorTemperature);
Assert.Equal(6, m.Orientation);
Assert.Equal(4000, m.Width);
Assert.Equal(3000, m.Height);
Assert.Equal((3000, 4000), m.OrientedSize);
Assert.Equal(8, m.BitsPerSample);
var gps = Assert.NotNull(m.Gps);
Assert.Approximately(45.5, gps.Latitude, 1e-9);
Assert.Approximately(-9.26, gps.Longitude, 1e-9);
Assert.Approximately(120.5, gps.Altitude!.Value, 1e-9);
Assert.Equal(new DateTime(2024, 5, 1, 10, 34, 56, DateTimeKind.Utc), gps.UtcTimestamp);
Assert.Equal(4, m.Rating);
Assert.Equal("Red", m.Label);
AssertPreviews(m, (1920, 1440, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail));
}
[Test]
public void PreviewOffsetsPointAtJpegData()
{
var bytes = Fixtures.Jpeg();
var m = Read(bytes);
foreach (var p in m.Previews)
{
Assert.Equal(0xFF, bytes[p.Offset]);
Assert.Equal(0xD8, bytes[p.Offset + 1]);
Assert.Equal(0xD9, bytes[p.Offset + p.Length - 1]);
}
}
[Test]
public void FallsBackToDigitizedTime()
{
var m = ReadWithExif(Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal));
Assert.Equal(TimestampSource.ExifCreate, m.TimestampSource);
Assert.Equal(new DateTime(2024, 5, 1, 12, 34, 57), m.CapturedAt);
}
[Test]
public void FallsBackToXmpTime()
{
var xmp = """
<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:CreateDate="2023-12-31T23:59:58.25-05:00"/>
</rdf:RDF></x:xmpmeta>
""";
var exif = Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal, TiffTags.DateTimeDigitized);
var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif))).Xmp(xmp).Build(64, 48);
var m = Read(jpeg);
Assert.Equal(TimestampSource.Xmp, m.TimestampSource);
Assert.Equal(new DateTime(2023, 12, 31, 23, 59, 58, 250), m.CapturedAt);
Assert.Equal(-300, m.UtcOffsetMinutes);
}
[Test]
public void FallsBackToGpsTime()
{
var exif = Fixtures.ExifIfd().Without(TiffTags.DateTimeOriginal, TiffTags.DateTimeDigitized);
var m = ReadWithExif(exif);
Assert.Equal(TimestampSource.Gps, m.TimestampSource);
Assert.Equal(new DateTime(2024, 5, 1, 10, 34, 56), m.CapturedAt);
Assert.Equal(DateTimeKind.Unspecified, m.CapturedAt!.Value.Kind);
Assert.Equal(0, m.UtcOffsetMinutes);
}
[Theory]
[Case(DateTimeKind.Utc, 0)]
[Case(DateTimeKind.Unspecified, null)]
public void FallsBackToFileTime(DateTimeKind kind, int? expectedOffset)
{
var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0())).Build(64, 48);
var modified = new DateTime(2022, 2, 3, 4, 5, 6, kind);
var m = Read(jpeg, null, modified);
Assert.Equal(TimestampSource.FileSystem, m.TimestampSource);
Assert.Equal(new DateTime(2022, 2, 3, 4, 5, 6), m.CapturedAt);
Assert.Equal(expectedOffset, m.UtcOffsetMinutes);
}
[Test]
public void LocalFileTimeCarriesLocalOffset()
{
var modified = new DateTime(2022, 7, 3, 4, 5, 6, DateTimeKind.Local);
var m = Read(JpegBuilder.Minimal(8, 8), null, modified);
Assert.Equal((int)TimeZoneInfo.Local.GetUtcOffset(modified).TotalMinutes, m.UtcOffsetMinutes);
}
[Test]
public void NoTimeAtAllIsUnknown()
{
var m = Read(JpegBuilder.Minimal(8, 8));
Assert.Equal(TimestampSource.Unknown, m.TimestampSource);
Assert.Null(m.CapturedAt);
}
[Theory]
[Case("5", "+05:30", 5_000_000L, 330)]
[Case("123456789", "-03:00", 1_234_567L, -180)]
[Case("007", "+0100", 70_000L, 60)]
[Case("", "Z", 0L, 0)]
[Case(" ", " : ", 0L, null)]
[Case("12x", "+25:00", 1_200_000L, null, Name = "trailing junk, offset out of range")]
public void ParsesSubSecondsAndOffsets(string subSec, string offset, long ticks, int? minutes)
{
var exif = Fixtures.ExifIfd().Ascii(TiffTags.SubSecTimeOriginal, subSec).Ascii(TiffTags.OffsetTimeOriginal, offset);
var m = ReadWithExif(exif);
Assert.Equal(new DateTime(2024, 5, 1, 12, 34, 56).AddTicks(ticks), m.CapturedAt);
Assert.Equal(minutes, m.UtcOffsetMinutes);
}
[Test]
public void OffsetTimeIsTheFallbackOffset()
{
var exif = Fixtures.ExifIfd().Without(TiffTags.OffsetTimeOriginal).Ascii(TiffTags.OffsetTime, "-07:00");
Assert.Equal(-420, ReadWithExif(exif).UtcOffsetMinutes);
}
[Theory]
[Case("0000:00:00 00:00:00")]
[Case(" : : : : ")]
[Case("2024:13:01 10:00:00")]
[Case("2024:02:30 10:00:00")]
[Case("2024:05")]
public void RejectsInvalidDates(string value)
{
var exif = Fixtures.ExifIfd().Ascii(TiffTags.DateTimeOriginal, value);
Assert.Equal(TimestampSource.ExifCreate, ReadWithExif(exif).TimestampSource);
}
[Theory]
[Case((ushort)1, 1)]
[Case((ushort)3, 3)]
[Case((ushort)5, 5)]
[Case((ushort)8, 8)]
[Case((ushort)0, 1)]
[Case((ushort)9, 1)]
public void ValidatesOrientation(ushort value, int expected)
{
var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0(orientation: value))).Build(64, 48));
Assert.Equal(expected, m.Orientation);
if (value is 0 or 9) Assert.Contains($"Invalid orientation {value} ignored", m.Warnings);
}
[Test]
public void XmpOrientationAppliesWithoutExif()
{
var xmp = """<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:tiff="http://ns.adobe.com/tiff/1.0/"><tiff:Orientation>3</tiff:Orientation></rdf:Description></rdf:RDF></x:xmpmeta>""";
Assert.Equal(3, Read(new JpegBuilder().Xmp(xmp).Build(64, 48)).Orientation);
}
[Theory]
[Case((ushort)65535, 102400u, 102400)]
[Case((ushort)65535, 0u, 65535, Name = "saturated without REI")]
[Case((ushort)0, 51200u, 51200, Name = "ISO absent")]
[Case((ushort)3200, 6400u, 3200, Name = "ISO wins when valid")]
public void ResolvesIso(ushort iso, uint rei, int expected)
{
var exif = Fixtures.ExifIfd(iso: iso);
if (rei > 0) exif.Long(TiffTags.RecommendedExposureIndex, rei);
Assert.Equal(expected, ReadWithExif(exif).Iso);
}
[Test]
public void UsesStandardOutputSensitivityWhenIsoMissing()
{
var exif = Fixtures.ExifIfd(iso: 0).Long(TiffTags.StandardOutputSensitivity, 250);
Assert.Equal(250, ReadWithExif(exif).Iso);
}
[Test]
public void DerivesExposureFromApexValues()
{
var exif = Fixtures.ExifIfd().Without(TiffTags.FNumber, TiffTags.ExposureTime)
.SRational(TiffTags.ShutterSpeedValue, 8, 1)
.Rational(TiffTags.ApertureValue, (5, 1));
var m = ReadWithExif(exif);
Assert.Approximately(1 / 256.0, m.ExposureTime!.Value, 1e-12);
Assert.Approximately(Math.Pow(2, 2.5), m.FNumber!.Value, 1e-12);
}
[Test]
public void IgnoresVoidGpsFix()
{
var gps = Fixtures.GpsIfd().Ascii(TiffTags.GpsStatus, "V");
var tiff = TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.GpsIfd, gps));
var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48));
Assert.Null(m.Gps);
Assert.Equal(TimestampSource.Gps, m.TimestampSource);
}
[Test]
public void RejectsOutOfRangeCoordinates()
{
var gps = Fixtures.GpsIfd().Rational(TiffTags.GpsLatitude, (95, 1), (0, 1), (0, 1));
var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.GpsIfd, gps))).Build(64, 48));
Assert.Null(m.Gps);
}
[Test]
public void ToleratesFillBytesAndGarbageBetweenSegments()
{
var jpeg = new JpegBuilder()
.Raw(0xFF, 0xFF, 0xFF)
.Exif(Fixtures.ExifTiff())
.Raw(0x00, 0x13, 0x37, 0xFF)
.Segment(0xFE, "comment"u8.ToArray())
.Build(1234, 567);
var m = Read(jpeg);
Assert.Equal(1234, m.Width);
Assert.Equal(567, m.Height);
Assert.Equal(Fixtures.Make, m.Make);
Assert.Contains("JPEG: garbage between segments skipped", m.Warnings);
}
[Theory]
[Case((byte)0xC2, 8)]
[Case((byte)0xC1, 12)]
public void ReadsProgressiveAndExtendedFrames(byte sof, int precision)
{
var m = Read(JpegBuilder.Minimal(800, 600, sof, precision));
Assert.Equal((800, 600), (m.Width, m.Height));
Assert.Equal(precision, m.BitsPerSample);
}
[Test]
public void TruncatedExifKeepsWhatWasRead()
{
var full = Fixtures.Jpeg();
var cut = full.AsSpan(0, 140).ToArray();
var m = Read(cut);
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Jpeg, m.Format);
Assert.NotEmpty(m.Warnings);
}
private static FrameMetadata ReadWithExif(IfdSpec exif) =>
Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif).Child(TiffTags.GpsIfd, Fixtures.GpsIfd()))).Build(64, 48));
}
@@ -0,0 +1,147 @@
using System.Buffers.Binary;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Model;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
public sealed class ExifWriterTests
{
private static readonly FrameMetadata Sample = new()
{
Make = "TestCam",
Model = "TC-1 Mark II",
Orientation = 8,
Software = "Chronos 1.0",
Artist = "Ada Lovelace",
Copyright = "© 2024 Ada",
CapturedAt = new DateTime(2024, 5, 1, 12, 34, 56).AddTicks(1_234_500),
UtcOffsetMinutes = -330,
ExposureTime = 1 / 8000.0,
FNumber = 2.8,
Iso = 3200,
FocalLength = 23.5,
FocalLength35 = 35,
ExposureBias = -1 / 3.0,
BodySerial = "BODY-42",
LensModel = "XF23mmF1.4 R",
Gps = new GpsPosition(-33.8567844, 151.2152967, -12.25, new DateTime(2024, 5, 1, 2, 4, 56, 500, DateTimeKind.Utc)),
};
[Test]
public void RoundTripsThroughMetadataReader()
{
var m = Read(Wrap(ExifWriter.BuildJpegApp1(Sample)));
AssertNoFault(m);
Assert.Equal(Sample.Make, m.Make);
Assert.Equal(Sample.Model, m.Model);
Assert.Equal(8, m.Orientation);
Assert.Equal(Sample.Software, m.Software);
Assert.Equal(Sample.Artist, m.Artist);
Assert.Equal(Sample.Copyright, m.Copyright);
Assert.Equal(Sample.CapturedAt, m.CapturedAt);
Assert.Equal(-330, m.UtcOffsetMinutes);
Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource);
Assert.Approximately(Sample.ExposureTime!.Value, m.ExposureTime!.Value, 1e-15);
Assert.Approximately(2.8, m.FNumber!.Value, 1e-12);
Assert.Equal(3200, m.Iso);
Assert.Approximately(23.5, m.FocalLength!.Value, 1e-12);
Assert.Approximately(35, m.FocalLength35!.Value, 1e-12);
Assert.Approximately(-1 / 3.0, m.ExposureBias!.Value, 1e-4);
Assert.Equal(Sample.BodySerial, m.BodySerial);
Assert.Equal(Sample.LensModel, m.LensModel);
var gps = Assert.NotNull(m.Gps);
Assert.Approximately(-33.8567844, gps.Latitude, 1e-7);
Assert.Approximately(151.2152967, gps.Longitude, 1e-7);
Assert.Approximately(-12.25, gps.Altitude!.Value, 1e-9);
Assert.Equal(Sample.Gps!.UtcTimestamp, gps.UtcTimestamp);
}
[Test]
public void App1SegmentIsWellFormed()
{
var app1 = ExifWriter.BuildJpegApp1(Sample);
Assert.Equal(0xFF, app1[0]);
Assert.Equal(0xE1, app1[1]);
Assert.Equal(app1.Length - 2, BinaryPrimitives.ReadUInt16BigEndian(app1.AsSpan(2)));
Assert.True(app1.AsSpan(4).StartsWith("Exif\0\0II*\0"u8));
}
[Test]
public void TiffIsSortedAndPointersResolve()
{
var tiff = ExifWriter.BuildTiff(Sample);
var reader = Assert.NotNull(TiffReader.Open(new MemoryStream(tiff)));
Assert.True(reader.LittleEndian);
var chain = reader.ReadChain();
Assert.Equal(1, chain.Count);
var ifd0 = chain[0];
AssertSorted(reader, ifd0);
var exif = Assert.NotNull(reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value));
AssertSorted(reader, exif);
Assert.Equal("0232", reader.GetString(exif, TiffTags.ExifVersion));
Assert.NotNull(reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.GpsIfd)!.Value));
Assert.Empty(reader.Warnings);
}
[Test]
public void OmitsUnknownValuesAndGps()
{
var tiff = ExifWriter.BuildTiff(new FrameMetadata { Make = "Only" });
var reader = TiffReader.Open(new MemoryStream(tiff))!;
var ifd0 = reader.ReadChain()[0];
Assert.False(ifd0.Has(TiffTags.GpsIfd));
Assert.False(ifd0.Has(TiffTags.DateTime));
Assert.Equal((ushort)1, (ushort)reader.GetUInt(ifd0, TiffTags.Orientation)!.Value);
var exif = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)!;
Assert.False(exif.Has(TiffTags.ExposureTime));
Assert.False(exif.Has(TiffTags.SubSecTimeOriginal));
Assert.False(exif.Has(TiffTags.OffsetTimeOriginal));
}
[Test]
public void HighIsoUsesRecommendedExposureIndex()
{
var m = Read(Wrap(ExifWriter.BuildJpegApp1(Sample with { Iso = 204800 })));
Assert.Equal(204800, m.Iso);
}
[Theory]
[Case(1 / 8000.0, 1u, 8000u)]
[Case(0.3, 3u, 10u)]
[Case(2.8, 14u, 5u)]
[Case(30.0, 30u, 1u)]
public void EncodesExposureRationals(double seconds, uint numerator, uint denominator)
{
var tiff = ExifWriter.BuildTiff(new FrameMetadata { ExposureTime = seconds });
var reader = TiffReader.Open(new MemoryStream(tiff))!;
var exif = reader.ReadIfd(reader.GetUInt(reader.ReadChain()[0], TiffTags.ExifIfd)!.Value)!;
var raw = reader.ReadBytes(exif.Entries[TiffTags.ExposureTime])!;
Assert.Equal(numerator, BinaryPrimitives.ReadUInt32LittleEndian(raw));
Assert.Equal(denominator, BinaryPrimitives.ReadUInt32LittleEndian(raw.AsSpan(4)));
}
[Test]
public void TruncatesLongStringsOnCharacterBoundaries()
{
var longText = new string('é', ExifWriter.MaxStringBytes);
var app1 = ExifWriter.BuildJpegApp1(new FrameMetadata { Artist = longText, Copyright = longText, Make = longText, Model = longText, Software = longText, BodySerial = longText, LensModel = longText });
Assert.Less(app1.Length, 65535);
var m = Read(Wrap(app1));
Assert.Equal(ExifWriter.MaxStringBytes / 2, m.Artist!.Length);
Assert.True(m.Artist.All(c => c == 'é'));
}
/// <summary>SOI + APP1 + a minimal 64×48 frame.</summary>
private static byte[] Wrap(byte[] app1) => [0xFF, 0xD8, .. app1, .. Builders.JpegBuilder.Minimal(64, 48).AsSpan(2)];
private static void AssertSorted(TiffReader reader, Ifd ifd)
{
var count = BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position, 2)!);
var tags = new List<double>();
for (var i = 0; i < count; i++) tags.Add(BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position + 2 + 12 * i, 2)!));
Assert.Monotonic(tags, strict: true);
}
}
@@ -0,0 +1,112 @@
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
namespace Chronos.Core.Tests.Metadata;
public sealed class ImageSignatureTests
{
[Theory]
[Case("jpeg", "a.jpg", ImageFileFormat.Jpeg)]
[Case("jpeg", "a.png", ImageFileFormat.Jpeg, Name = "extension never overrides the signature")]
[Case("png", null, ImageFileFormat.Png)]
[Case("webp", null, ImageFileFormat.WebP)]
[Case("raf", "a.jpg", ImageFileFormat.Raf)]
[Case("cr2", "a.tif", ImageFileFormat.Cr2, Name = "CR marker beats .tif")]
[Case("cr3", null, ImageFileFormat.Cr3)]
[Case("heic", null, ImageFileFormat.Heif)]
[Case("avif", null, ImageFileFormat.Avif)]
[Case("nef", null, ImageFileFormat.Nef)]
[Case("nef", "x.NRW", ImageFileFormat.Nrw)]
[Case("nef", "x.tif", ImageFileFormat.Tiff, Name = "Nikon-made TIFF")]
[Case("arw", "x.arw", ImageFileFormat.Arw)]
[Case("arw", "x.sr2", ImageFileFormat.Sr2)]
[Case("arw", "x.srf", ImageFileFormat.Srf)]
[Case("dng", "x.dng", ImageFileFormat.Dng)]
[Case("dng", "x.gpr", ImageFileFormat.Gpr)]
[Case("dng", "x.tif", ImageFileFormat.Dng, Name = "DNGVersion beats .tif")]
[Case("orf", null, ImageFileFormat.Orf)]
[Case("rw2", null, ImageFileFormat.Rw2)]
[Case("rw2", "x.rwl", ImageFileFormat.Rwl)]
[Case("rw2", "x.raw", ImageFileFormat.Raw)]
public void DetectsFixtures(string fixture, string? fileName, ImageFileFormat expected) =>
Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(Fixtures.ByName(fixture)), fileName));
[Theory]
[Case("PENTAX Corporation", null, ImageFileFormat.Pef)]
[Case("RICOH IMAGING COMPANY, LTD.", null, ImageFileFormat.Pef)]
[Case("SAMSUNG", null, ImageFileFormat.Srw)]
[Case("Hasselblad", null, ImageFileFormat.ThreeFr)]
[Case("Hasselblad", "x.fff", ImageFileFormat.Fff)]
[Case("Phase One", null, ImageFileFormat.Iiq)]
[Case("Leaf", null, ImageFileFormat.Iiq)]
[Case("Canon", "x.cr2", ImageFileFormat.Cr2, Name = "Canon without CR marker, .cr2")]
[Case("Canon", null, ImageFileFormat.Tiff)]
[Case("OLYMPUS", "x.orf", ImageFileFormat.Orf)]
[Case("Scanner Inc", "x.pef", ImageFileFormat.Pef, Name = "unknown make, raw extension breaks the tie")]
[Case("Scanner Inc", null, ImageFileFormat.Tiff)]
[Case("SAMSUNG", "x.tiff", ImageFileFormat.Tiff, Name = ".tiff keeps a camera-made TIFF a TIFF")]
public void RefinesTiffByMake(string make, string? fileName, ImageFileFormat expected)
{
var tiff = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, make).Long(TiffTags.ImageWidth, 8), littleEndian: false);
Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(tiff), fileName));
}
[Theory]
[Case("LEICA CAMERA AG", null, ImageFileFormat.Rwl)]
[Case("Panasonic", null, ImageFileFormat.Rw2)]
public void PanasonicHeaderUsesMake(string make, string? fileName, ImageFileFormat expected)
{
var rw = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, make), magic: "IIU\0");
Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(rw), fileName));
}
[Theory]
[Case("mif1", "heic", ImageFileFormat.Heif)]
[Case("mif1", "avif", ImageFileFormat.Avif)]
[Case("msf1", "hevc", ImageFileFormat.Heif)]
[Case("heix", "mif1", ImageFileFormat.Heif)]
[Case("avis", "msf1", ImageFileFormat.Avif)]
[Case("qt ", "qt ", ImageFileFormat.Unknown, Name = "QuickTime movie")]
[Case("isom", "mp41", ImageFileFormat.Unknown, Name = "MP4 video")]
public void ClassifiesFtypBrands(string major, string compatible, ImageFileFormat expected)
{
var ftyp = Box.Make("ftyp", Box.Ascii(major), Box.U32(0), Box.Ascii(compatible));
Assert.Equal(expected, ImageSignature.Detect(new MemoryStream([.. ftyp, .. Box.Make("free")]), null));
}
[Theory]
[Case(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a', 1, 0, 1, 0 }, ImageFileFormat.Gif)]
[Case(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'7', (byte)'a', 1, 0, 1, 0 }, ImageFileFormat.Gif)]
[Case(new byte[] { 0xFF, 0x0A, 0x7F, 0 }, ImageFileFormat.JpegXl)]
[Case(new byte[] { 0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A }, ImageFileFormat.JpegXl)]
[Case(new byte[] { (byte)'I', (byte)'I', 0xBC, 0x01, 8, 0, 0, 0 }, ImageFileFormat.JpegXr)]
[Case(new byte[] { (byte)'I', (byte)'I', 0x1A, 0, 0, 0, (byte)'H', (byte)'E', (byte)'A', (byte)'P', (byte)'C', (byte)'C', (byte)'D', (byte)'R' }, ImageFileFormat.Crw)]
[Case(new byte[] { (byte)'M', (byte)'M', (byte)'O', (byte)'R', 0, 0, 0, 8 }, ImageFileFormat.Orf)]
[Case(new byte[] { 0xFF, 0xD8, 0xFF, 0xE1 }, ImageFileFormat.Jpeg)]
[Case(new byte[] { 0xFF, 0xD8 }, ImageFileFormat.Unknown, Name = "two bytes of SOI only")]
[Case(new byte[] { (byte)'B', (byte)'M', 0, 0 }, ImageFileFormat.Unknown, Name = "BM without a DIB header")]
[Case(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, ImageFileFormat.Unknown)]
[Case(new byte[0], ImageFileFormat.Unknown)]
public void DetectsMagicBytes(byte[] head, ImageFileFormat expected) =>
Assert.Equal(expected, ImageSignature.Detect(new MemoryStream(head), "file.jpg"));
[Test]
public void DetectsBmpWithInfoHeader()
{
var bmp = new byte[54];
"BM"u8.CopyTo(bmp);
bmp[14] = 40;
Assert.Equal(ImageFileFormat.Bmp, ImageSignature.Detect(new MemoryStream(bmp), null));
}
[Test]
public void RestoresStreamPosition()
{
var stream = new MemoryStream(Fixtures.Nef()) { Position = 5 };
ImageSignature.Detect(stream, null);
Assert.Equal(5L, stream.Position);
}
}
@@ -0,0 +1,125 @@
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
/// <summary>
/// MakerNote fields of BRIEF §9 beyond identity: the vendor exposure mode (when Exif has no ExposureProgram), the
/// intervalometer hint and the reduced-size RAW flag, from synthetic vendor IFDs.
/// </summary>
public sealed class MakerNoteTests
{
/// <summary>A JPEG whose Exif lacks ExposureProgram and carries <paramref name="makerNote"/> after <paramref name="prefix"/>.</summary>
private static FrameMetadata Jpeg(string make, string model, byte[] prefix, IfdSpec makerNote, bool relativeToTiff = true, bool keepProgram = false)
{
var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, prefix, makerNote, relativeToTiff, littleEndian: true);
if (!keepProgram) exif.Without(TiffTags.ExposureProgram);
var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0(make, model, 1).Child(TiffTags.ExifIfd, exif))).Build(64, 48));
AssertNoFault(m);
return m;
}
/// <summary>A CR2 ("CR" header block) with only IFD0, the Exif IFD and a Canon MakerNote.</summary>
private static FrameMetadata Cr2(ushort[] cameraSettings)
{
var makerNote = new IfdSpec().Short(0x0001, cameraSettings);
var exif = Fixtures.ExifIfd(identity: false).Without(TiffTags.ExposureProgram)
.Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true);
var ifd0 = Fixtures.Ifd0("Canon", "Canon EOS 5D Mark IV", 1).Child(TiffTags.ExifIfd, exif);
var m = Read(TiffFile.Build(ifd0, true, headerExtra: [(byte)'C', (byte)'R', 2, 0, 0, 0, 0, 0]), "IMG_0001.CR2");
AssertNoFault(m);
return m;
}
private static ushort[] CanonSettings(ushort exposureMode, ushort sRawQuality) =>
[.. Enumerable.Range(0, 48).Select(i => (ushort)(i switch { 20 => exposureMode, 46 => sRawQuality, _ => 0 }))];
[Theory]
[Case(1, 2)]
[Case(2, 4)]
[Case(3, 3)]
[Case(4, 1)]
[Case(5, 5)]
[Case(7, 1)]
[Case(8, 2)]
public void CanonExposureModeFillsTheExposureProgram(int canonMode, int exposureProgram)
{
var m = Jpeg("Canon", "Canon EOS R6", [], new IfdSpec().Short(0x0001, CanonSettings((ushort)canonMode, 0)));
Assert.Equal(exposureProgram, m.ExposureProgram);
// Not a RAW: the sRAW field says nothing about a JPEG.
Assert.Null(m.RawSize);
}
[Test]
public void CanonEasyModeLeavesTheProgramUnknownAndExifWins()
{
Assert.Null(Jpeg("Canon", "Canon EOS R6", [], new IfdSpec().Short(0x0001, CanonSettings(0, 0))).ExposureProgram);
// The fixture's Exif says aperture priority (3); the MakerNote's manual mode does not override it.
Assert.Equal(3, Jpeg("Canon", "Canon EOS R6", [], new IfdSpec().Short(0x0001, CanonSettings(4, 0)), keepProgram: true).ExposureProgram);
}
[Theory]
[Case(0, RawSize.Full)]
[Case(1, RawSize.Medium)]
[Case(2, RawSize.Small)]
public void CanonSRawQualityGivesTheRawSize(int quality, RawSize expected)
{
var m = Cr2(CanonSettings(3, (ushort)quality));
Assert.Equal(ImageFileFormat.Cr2, m.Format);
Assert.Equal(expected, m.RawSize);
Assert.Equal(3, m.ExposureProgram);
// Bodies whose settings stop before the sRAW field record no size.
Assert.Null(Cr2([.. CanonSettings(3, (ushort)quality).Take(40)]).RawSize);
}
[Test]
public void NikonRawSizeComesFromImageSizeRawOrTheSmallNefCompression()
{
static FrameMetadata Nikon(IfdSpec ifd) => Jpeg("NIKON CORPORATION", "NIKON Z 8", [], ifd);
Assert.Equal(RawSize.Medium, Nikon(new IfdSpec().Short(0x003E, 2)).RawSize);
Assert.Equal(RawSize.Small, Nikon(new IfdSpec().Short(0x003E, 3)).RawSize);
Assert.Equal(RawSize.Full, Nikon(new IfdSpec().Short(0x003E, 1).Short(0x0093, 3)).RawSize);
Assert.Equal(RawSize.Small, Nikon(new IfdSpec().Short(0x0093, 8)).RawSize);
Assert.Null(Nikon(new IfdSpec().Short(0x0093, 3)).RawSize);
// Nikon keeps interval shooting in its encrypted ShotInfo only.
Assert.Null(Nikon(new IfdSpec().Short(0x003E, 1)).IntervalShooting);
}
[Test]
public void OlympusFujifilmAndSonyExposureModes()
{
var olympus = Jpeg("OLYMPUS", "E-M1MarkIII", [.. "OLYMP\0"u8, 1, 0], new IfdSpec().Child(0x2020, new IfdSpec().Short(0x0200, 4)));
Assert.Equal(4, olympus.ExposureProgram);
var fuji = Jpeg("FUJIFILM", "X-T5", [.. "FUJIFILM"u8, 12, 0, 0, 0], new IfdSpec().Short(0x1031, 0x300), relativeToTiff: false);
Assert.Equal(1, fuji.ExposureProgram);
var fujiAperture = Jpeg("FUJIFILM", "X-T5", [.. "FUJIFILM"u8, 12, 0, 0, 0], new IfdSpec().Short(0x1031, 0x100), relativeToTiff: false);
Assert.Equal(3, fujiAperture.ExposureProgram);
var sony = Jpeg("SONY", "ILCE-7M4", [.. "SONY DSC \0\0\0"u8], new IfdSpec().Short(0xB041, 8));
Assert.Equal(4, sony.ExposureProgram);
var sonyAuto = Jpeg("SONY", "ILCE-7M4", [.. "SONY DSC \0\0\0"u8], new IfdSpec().Short(0xB041, 6));
Assert.Null(sonyAuto.ExposureProgram);
}
[Theory]
[Case(1, true)]
[Case(0, false)]
[Case(2, false)]
[Case(3, false)]
public void PanasonicTimerRecordingIsTheIntervalometerHint(int timerRecording, bool expected)
{
var m = Jpeg("Panasonic", "DC-GH6", [.. "Panasonic\0\0\0"u8], new IfdSpec().Short(0x001F, 11).Short(0x0096, (ushort)timerRecording));
Assert.Equal(expected, m.IntervalShooting);
Assert.Equal(1, m.ExposureProgram);
}
[Test]
public void WithoutTheTagsNothingIsGuessed()
{
var m = Jpeg("Panasonic", "DC-GH6", [.. "Panasonic\0\0\0"u8], new IfdSpec().Short(0x001A, 2));
Assert.Equal(((bool?)null, (RawSize?)null, (int?)null), (m.IntervalShooting, m.RawSize, m.ExposureProgram));
}
}
@@ -0,0 +1,25 @@
using Chronos.Core.Metadata;
using Chronos.Testing;
namespace Chronos.Core.Tests.Metadata;
internal static class MetadataTestHelpers
{
public static FrameMetadata Read(byte[] data, string? fileName = null, DateTime? modified = null) =>
MetadataReader.Read(new MemoryStream(data, writable: false), fileName, modified);
/// <summary>The reader's safety net turns parser defects into "Parser fault" warnings; tests require none.</summary>
public static void AssertNoFault(FrameMetadata m)
{
foreach (var w in m.Warnings)
{
if (w.StartsWith("Parser fault", StringComparison.Ordinal)) Assert.Fail(w);
}
}
public static void AssertPreviews(FrameMetadata m, params (int Width, int Height, PreviewKind Kind)[] expected)
{
Assert.SequenceEqual(expected, m.Previews.Select(p => (p.Width, p.Height, p.Kind)), "previews");
foreach (var p in m.Previews) Assert.True(p.Offset > 0 && p.Length > 0, $"preview at {p.Offset} length {p.Length}");
}
}
@@ -0,0 +1,202 @@
using System.Buffers.Binary;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
/// <summary>RAF, WebP, PNG and the minimal formats (GIF, BMP, JPEG XL, JPEG XR).</summary>
public sealed class OtherFormatTests
{
[Test]
public void Raf()
{
var m = Read(Fixtures.Raf(), "DSCF0001.RAF");
AssertNoFault(m);
Assert.Empty(m.Warnings);
Assert.Equal(ImageFileFormat.Raf, m.Format);
Assert.Equal("FUJIFILM", m.Make);
Assert.Equal("X-T5", m.Model);
Assert.Equal((7752, 5178), (m.Width, m.Height));
Assert.Equal(14, m.BitsPerSample);
AssertPreviews(m, (1920, 1280, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail));
Assert.Equal("FF02B1234567", m.BodySerial);
Assert.Equal(6100, m.ColorTemperature);
Assert.Equal(true, m.ImageStabilization);
Assert.Equal(Fixtures.Captured, m.CapturedAt);
}
[Test]
public void RafHeaderModelIsTheFallback()
{
var raf = Fixtures.Raf();
BinaryPrimitives.WriteUInt32BigEndian(raf.AsSpan(0x54), 0);
var m = Read(raf);
Assert.Equal("FUJIFILM", m.Make);
Assert.Equal("X-T5", m.Model);
Assert.Equal((7752, 5178), (m.Width, m.Height));
Assert.Contains("RAF embedded JPEG missing", m.Warnings);
}
[Test]
public void WebPWithVp8xExifAndXmp()
{
var m = Read(Fixtures.WebP(), "a.webp");
AssertNoFault(m);
Assert.Empty(m.Warnings);
Assert.Equal(ImageFileFormat.WebP, m.Format);
Assert.Equal((3000, 2000), (m.Width, m.Height));
Assert.Equal(8, m.BitsPerSample);
Assert.Equal(Fixtures.Make, m.Make);
Assert.Equal(Fixtures.Captured, m.CapturedAt);
Assert.Equal(4, m.Rating);
Assert.Equal(6, m.Orientation);
}
[Test]
public void WebPSimpleFormats()
{
Assert.Equal((640, 480), Size(Read(Fixtures.WebPLossy(640, 480))));
var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8L", Fixtures.Vp8L(400, 300))];
Assert.Equal((400, 300), Size(Read([.. "RIFF"u8, .. LittleEndian(body.Length), .. body])));
}
[Test]
public void WebPExifWithPrefix()
{
var body = (byte[])[.. "WEBP"u8, .. Box.Riff("VP8L", Fixtures.Vp8L(8, 8)), .. Box.Riff("EXIF", [.. "Exif\0\0"u8, .. Fixtures.ExifTiff()])];
Assert.Equal(Fixtures.Model, Read([.. "RIFF"u8, .. LittleEndian(body.Length), .. body]).Model);
}
[Theory]
[Case(false)]
[Case(true)]
public void Png(bool compressedXmp)
{
var m = Read(Fixtures.Png(compressedXmp), "a.png");
AssertNoFault(m);
Assert.Empty(m.Warnings);
Assert.Equal(ImageFileFormat.Png, m.Format);
Assert.Equal((2048, 1536), (m.Width, m.Height));
Assert.Equal(16, m.BitsPerSample);
Assert.Equal(Fixtures.Model, m.Model);
Assert.Equal(400, m.Iso);
Assert.Equal("Red", m.Label);
}
[Test]
public void Gif() => Assert.Equal((320, 200), Size(Read([.. "GIF89a"u8, 0x40, 0x01, 0xC8, 0x00, 0, 0, 0])));
[Theory]
[Case(40, 640, -480)]
[Case(124, 1024, 768)]
public void Bmp(int headerSize, int width, int height)
{
var bmp = new byte[54];
"BM"u8.CopyTo(bmp);
BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(14), headerSize);
BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(18), width);
BinaryPrimitives.WriteInt32LittleEndian(bmp.AsSpan(22), height);
Assert.Equal((width, Math.Abs(height)), Size(Read(bmp)));
}
[Test]
public void BmpCoreHeader()
{
var bmp = new byte[26];
"BM"u8.CopyTo(bmp);
bmp[14] = 12;
BinaryPrimitives.WriteUInt16LittleEndian(bmp.AsSpan(18), 300);
BinaryPrimitives.WriteUInt16LittleEndian(bmp.AsSpan(20), 200);
Assert.Equal((300, 200), Size(Read(bmp)));
}
[Theory]
[Case(256, 128)]
[Case(1000, 750, Name = "4:3 ratio")]
[Case(1921, 1081)]
[Case(300000, 270000, Name = "two 30-bit sizes (68-bit header)")]
public void JpegXlCodestream(int width, int height)
{
var m = Read(BuildJpegXlCodestream(width, height), "a.jxl");
Assert.Equal(ImageFileFormat.JpegXl, m.Format);
Assert.Equal((width, height), Size(m));
}
[Test]
public void JpegXlContainer()
{
byte[] file = [.. Box.Make("JXL ", [0x0D, 0x0A, 0x87, 0x0A]), .. Box.Make("ftyp", Box.Ascii("jxl "), Box.U32(0), Box.Ascii("jxl ")),
.. Box.Make("Exif", Box.U32(0), Fixtures.ExifTiff()), .. Box.Make("jxlp", Box.U32(0), BuildJpegXlCodestream(512, 384))];
var m = Read(file);
Assert.Equal(ImageFileFormat.JpegXl, m.Format);
Assert.Equal((512, 384), Size(m));
Assert.Equal(Fixtures.Make, m.Make);
}
[Test]
public void JpegXr()
{
var ifd = new IfdSpec().Ascii(TiffTags.Make, "Microsoft").Long(0xBC80, 1600).Long(0xBC81, 900);
var m = Read(TiffFile.Build(ifd, magic: "II¼\u0001"), "a.jxr");
Assert.Equal(ImageFileFormat.JpegXr, m.Format);
Assert.Equal((1600, 900), Size(m));
Assert.Equal("Microsoft", m.Make);
}
[Test]
public void UnknownFilesYieldAWarning()
{
var m = Read("hello world, not an image"u8.ToArray(), "notes.jpg");
Assert.Equal(ImageFileFormat.Unknown, m.Format);
Assert.Contains("Unrecognised file signature", m.Warnings);
}
private static (int, int) Size(FrameMetadata m) => (m.Width, m.Height);
private static byte[] LittleEndian(int v)
{
var b = new byte[4];
BinaryPrimitives.WriteInt32LittleEndian(b, v);
return b;
}
/// <summary>FF 0A + SizeHeader (ISO/IEC 18181-1): small multiples of 8 or U32 distributions; a 4:3 ratio when exact.</summary>
private static byte[] BuildJpegXlCodestream(int width, int height)
{
var bits = new List<bool>();
void Put(ulong value, int count)
{
for (var i = 0; i < count; i++) bits.Add(((value >> i) & 1) != 0);
}
void PutU32(int value)
{
var v = (ulong)(value - 1);
var (selector, n) = v < 1 << 9 ? (0, 9) : v < 1 << 13 ? (1, 13) : v < 1 << 18 ? (2, 18) : (3, 30);
Put((ulong)selector, 2);
Put(v, n);
}
var small = width % 8 == 0 && height % 8 == 0 && width <= 256 && height <= 256;
Put(small ? 1UL : 0UL, 1);
if (small) Put((ulong)(height / 8 - 1), 5);
else PutU32(height);
var ratio = height * 4 / 3 == width && height % 3 == 0 ? 3 : 0;
Put((ulong)ratio, 3);
if (ratio == 0)
{
if (small) Put((ulong)(width / 8 - 1), 5);
else PutU32(width);
}
var bytes = new byte[2 + (bits.Count + 7) / 8 + 8];
bytes[0] = 0xFF;
bytes[1] = 0x0A;
for (var i = 0; i < bits.Count; i++)
{
if (bits[i]) bytes[2 + i / 8] |= (byte)(1 << (i % 8));
}
return bytes;
}
}
@@ -0,0 +1,190 @@
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Model;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
/// <summary>TIFF-based RAWs: main-image selection across IFDs/SubIFDs, embedded previews and MakerNote fallbacks.</summary>
public sealed class RawContainerTests
{
[Test]
public void Cr2()
{
var m = Read(Fixtures.Cr2(), "IMG_0001.CR2");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Cr2, m.Format);
Assert.Equal("Canon", m.Make);
Assert.Equal((6720, 4480), (m.Width, m.Height));
Assert.Equal(14, m.BitsPerSample);
AssertPreviews(m, (6720, 4480, PreviewKind.FullSize), (160, 120, PreviewKind.Thumbnail));
Assert.Equal("0000123456", m.BodySerial);
Assert.Equal("EF24-70mm f/2.8L II USM", m.LensModel);
Assert.Equal(true, m.ImageStabilization);
Assert.Equal(5200, m.ColorTemperature);
Assert.Equal(Fixtures.Captured, m.CapturedAt);
Assert.Equal(1, m.Orientation);
}
[Test]
public void Nef()
{
var m = Read(Fixtures.Nef(), "DSC_0001.NEF");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Nef, m.Format);
Assert.Equal("NIKON CORPORATION", m.Make);
Assert.Equal((8288, 5520), (m.Width, m.Height));
Assert.Equal(14, m.BitsPerSample);
AssertPreviews(m, (8256, 5504, PreviewKind.FullSize));
Assert.Equal("3001234", m.BodySerial);
Assert.Equal(12345L, m.ShutterCount);
Assert.Equal("24-70mm f/2.8", m.LensModel);
Assert.Equal(true, m.ImageStabilization);
Assert.Equal(64, m.Iso);
}
[Test]
public void Dng()
{
var m = Read(Fixtures.Dng(), "PXL_0001.dng");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Dng, m.Format);
Assert.Equal((4032, 3024), (m.Width, m.Height));
Assert.Equal(16, m.BitsPerSample);
AssertPreviews(m, (1024, 768, PreviewKind.Preview));
Assert.Equal("DNGSER1", m.BodySerial);
Assert.Equal("Pixel 8", m.Model);
}
[Test]
public void Arw()
{
var m = Read(Fixtures.Arw(), "DSC00001.ARW");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Arw, m.Format);
Assert.Equal((6048, 4024), (m.Width, m.Height));
Assert.Equal(12, m.BitsPerSample);
AssertPreviews(m, (1616, 1080, PreviewKind.Preview));
Assert.Equal("24-70mm F2.8", m.LensModel);
Assert.Equal(5600, m.ColorTemperature);
Assert.Equal(true, m.ImageStabilization);
}
[Test]
public void Orf()
{
var m = Read(Fixtures.Orf(), "P0000001.ORF");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Orf, m.Format);
Assert.Equal((5240, 3912), (m.Width, m.Height));
Assert.Equal(12, m.BitsPerSample);
AssertPreviews(m, (3200, 2400, PreviewKind.Preview));
Assert.Equal("BHX123", m.BodySerial);
Assert.Equal("M.Zuiko 12-40mm F2.8", m.LensModel);
Assert.Equal(true, m.ImageStabilization);
}
[Test]
public void Rw2()
{
var m = Read(Fixtures.Rw2(), "P1000001.RW2");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Rw2, m.Format);
Assert.Equal("Panasonic", m.Make);
Assert.Equal("DC-GH6", m.Model);
Assert.Equal((5776, 4344), (m.Width, m.Height));
Assert.Equal(12, m.BitsPerSample);
Assert.Equal(800, m.Iso);
AssertPreviews(m, (1920, 1440, PreviewKind.Preview), (160, 120, PreviewKind.Thumbnail));
Assert.Equal("F541504040123", m.BodySerial);
Assert.Equal("LUMIX G VARIO 12-60mm", m.LensModel);
Assert.Equal(true, m.ImageStabilization);
Assert.Equal(5000, m.ColorTemperature);
Assert.Equal(TimestampSource.ExifOriginal, m.TimestampSource);
Assert.Equal(1, m.Orientation);
}
[Test]
public void StandardTagsBeatMakerNote()
{
var makerNote = new IfdSpec().Long(0x000C, 42).Ascii(0x0095, "MakerNote Lens");
var exif = Fixtures.ExifIfd().Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: true);
var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", "Canon EOS R6").Child(TiffTags.ExifIfd, exif));
var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48));
Assert.Equal("SN123", m.BodySerial);
Assert.Equal("TestLens 35mm", m.LensModel);
}
[Theory]
[Case("Canon EOS-1D X Mark III", "042000")]
[Case("Canon EOS R6", "0000042000")]
public void FormatsCanonSerialByModel(string model, string expected)
{
var makerNote = new IfdSpec().Long(0x000C, 42000);
var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], makerNote, relativeToTiff: true, littleEndian: false);
var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", model).Child(TiffTags.ExifIfd, exif), littleEndian: false);
Assert.Equal(expected, Read(new JpegBuilder().Exif(tiff).Build(64, 48)).BodySerial);
}
[Test]
public void ReadsHeaderlessNikonMakerNote()
{
var nikon = new IfdSpec().Ascii(0x001D, "TYPE2").Long(0x00A7, 7);
var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [], nikon, relativeToTiff: true, littleEndian: true);
var tiff = TiffFile.Build(Fixtures.Ifd0("NIKON", "E5700").Child(TiffTags.ExifIfd, exif));
var m = Read(new JpegBuilder().Exif(tiff).Build(64, 48));
Assert.Equal("TYPE2", m.BodySerial);
Assert.Equal(7L, m.ShutterCount);
}
[Test]
public void ReadsLegacyOlympusAndFujifilmMakerNotes()
{
var olympus = new IfdSpec().Child(0x2010, new IfdSpec().Ascii(0x0101, "OLD-SN"));
var exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "OLYMP\0"u8, 1, 0], olympus, relativeToTiff: true, littleEndian: true);
var m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0("OLYMPUS", "E-1").Child(TiffTags.ExifIfd, exif))).Build(64, 48));
Assert.Equal("OLD-SN", m.BodySerial);
var fuji = new IfdSpec().Short(0x1422, 0, 0, 0);
exif = Fixtures.ExifIfd(identity: false).Embedded(TiffTags.MakerNote, [.. "FUJIFILM"u8, 12, 0, 0, 0], fuji, relativeToTiff: false, littleEndian: true);
m = Read(new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0("FUJIFILM", "X100V").Child(TiffTags.ExifIfd, exif), littleEndian: false)).Build(64, 48));
Assert.Equal(false, m.ImageStabilization);
}
[Test]
public void MakerNoteOutsideFileIsReported()
{
var exif = Fixtures.ExifIfd(identity: false).Undefined(TiffTags.MakerNote, new byte[64]);
var tiff = TiffFile.Build(Fixtures.Ifd0("Canon", "Canon EOS R6").Child(TiffTags.ExifIfd, exif));
var cut = tiff.AsSpan(0, tiff.Length - 40).ToArray();
var m = Read(cut, "a.tif");
AssertNoFault(m);
Assert.Contains("MakerNote outside the file", m.Warnings);
}
[Test]
public void SubIfdLoopsAreBroken()
{
// IFD0's SubIFDs entry points back at IFD0 itself.
var tiff = TiffFile.Build(new IfdSpec().Ascii(TiffTags.Make, "Loop").Long(TiffTags.ImageWidth, 10).Long(TiffTags.ImageLength, 10).Long(TiffTags.SubIfds, 8));
var m = Read(tiff, "loop.tif");
AssertNoFault(m);
Assert.Equal((10, 10), (m.Width, m.Height));
Assert.Contains("IFD loop at 8", m.Warnings);
}
[Test]
public void PlainTiffUsesLargestFullResolutionIfd()
{
var reduced = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Long(TiffTags.ImageWidth, 9000).Long(TiffTags.ImageLength, 9000);
var ifd0 = new IfdSpec().Long(TiffTags.ImageWidth, 3000).Long(TiffTags.ImageLength, 2000).Short(TiffTags.BitsPerSample, 16, 16, 16);
ifd0.Next = reduced;
var m = Read(TiffFile.Build(ifd0, littleEndian: false), "scan.tif");
Assert.Equal(ImageFileFormat.Tiff, m.Format);
Assert.Equal((3000, 2000), (m.Width, m.Height));
Assert.Equal(16, m.BitsPerSample);
}
}
@@ -0,0 +1,189 @@
using System.Buffers.Binary;
using System.Diagnostics;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Model;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
/// <summary>Fuzzing, I/O bounds, speed, cancellation and file access.</summary>
public sealed class RobustnessTests(TestContext context)
{
private const int Truncations = 200;
private const int Corruptions = 500;
private const long FiftyMegabytes = 50L * 1024 * 1024;
private const long ReadBudget = 512 * 1024;
[Theory]
[Case("jpeg")]
[Case("jpeg-be")]
[Case("cr2")]
[Case("nef")]
[Case("dng")]
[Case("arw")]
[Case("orf")]
[Case("rw2")]
[Case("cr3")]
[Case("heic")]
[Case("avif")]
[Case("raf")]
[Case("webp")]
[Case("png")]
[Case("png-z")]
[Timeout(5000)]
public void SurvivesTruncationAndCorruption(string fixture)
{
var original = Fixtures.ByName(fixture);
var random = new Random(fixture.Aggregate(0x5EED, (seed, c) => seed * 31 + c));
var parses = 0;
for (var i = 0; i < Truncations; i++)
{
var length = (int)((long)original.Length * i / Truncations) + random.Next(0, 3);
Check(original.AsSpan(0, Math.Min(length, original.Length)).ToArray(), $"truncated at {length}");
parses++;
}
var buffer = new byte[original.Length];
for (var i = 0; i < Corruptions; i++)
{
original.CopyTo(buffer, 0);
var flips = random.Next(1, 9);
for (var f = 0; f < flips; f++) buffer[random.Next(buffer.Length)] = (byte)random.Next(256);
Check(buffer, $"corruption {i}");
parses++;
}
Assert.Equal(Truncations + Corruptions, parses);
}
[Test]
public void FuzzedFieldsStaySane()
{
var random = new Random(7);
var original = Fixtures.Jpeg();
for (var i = 0; i < 300; i++)
{
var bytes = (byte[])original.Clone();
for (var f = 0; f < 6; f++) bytes[random.Next(bytes.Length)] ^= (byte)(1 << random.Next(8));
var m = Read(bytes, "fuzz.jpg");
Assert.InRange(m.Orientation, 1, 8);
Assert.True(m.Width >= 0 && m.Height >= 0);
foreach (var p in m.Previews) Assert.True(p.Offset >= 0 && p.Offset + p.Length <= bytes.Length, "preview inside file");
}
}
[Test]
public void LargeDngReadsWellUnderHalfAMegabyte()
{
var preview = new IfdSpec().Long(TiffTags.NewSubfileType, 1).Long(TiffTags.ImageWidth, 4000).Long(TiffTags.ImageLength, 3000)
.Short(TiffTags.Compression, 7).Short(TiffTags.PhotometricInterpretation, 6)
.Strip(JpegBuilder.Minimal(4000, 3000, scanBytes: 1_500_000));
var raw = new IfdSpec().Long(TiffTags.NewSubfileType, 0).Long(TiffTags.ImageWidth, 8000).Long(TiffTags.ImageLength, 6000)
.Short(TiffTags.BitsPerSample, 16).Short(TiffTags.Compression, 7).Short(TiffTags.PhotometricInterpretation, 32803)
.Long(TiffTags.StripOffsets, 2_000_000).Long(TiffTags.StripByteCounts, 48_000_000);
var ifd0 = Fixtures.Ifd0("Leica Camera AG", "M11", 1).Long(TiffTags.NewSubfileType, 1).Bytes(TiffTags.DngVersion, 1, 6, 0, 0)
.Child(TiffTags.SubIfds, raw, preview).Child(TiffTags.ExifIfd, Fixtures.ExifIfd()).Child(TiffTags.GpsIfd, Fixtures.GpsIfd());
var bytes = TiffFile.Build(ifd0);
Assert.Less(bytes.Length, 2_000_000);
using var stream = new CountingStream(new SparseStream(bytes, FiftyMegabytes));
var m = MetadataReader.Read(stream, "L1000001.DNG");
AssertNoFault(m);
Assert.Equal(ImageFileFormat.Dng, m.Format);
Assert.Equal((8000, 6000), (m.Width, m.Height));
AssertPreviews(m, (4000, 3000, PreviewKind.Preview));
Assert.Equal(Fixtures.Captured, m.CapturedAt);
context.Log($"DNG: {stream.BytesRead} bytes in {stream.ReadCalls} reads");
Assert.Less(stream.BytesRead, ReadBudget);
}
[Test]
public void LargeCr3ReadsWellUnderHalfAMegabyte()
{
var bytes = Fixtures.Cr3(out var mdatStart);
BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(mdatStart), (uint)(FiftyMegabytes - mdatStart));
using var stream = new CountingStream(new SparseStream(bytes, FiftyMegabytes));
var m = MetadataReader.Read(stream, "IMG_0001.CR3");
AssertNoFault(m);
Assert.Equal((8352, 5586), (m.Width, m.Height));
Assert.Count(3, m.Previews);
context.Log($"CR3: {stream.BytesRead} bytes in {stream.ReadCalls} reads");
Assert.Less(stream.BytesRead, ReadBudget);
}
[Test]
public void ParsesTwoThousandJpegHeadersQuickly()
{
var jpeg = Fixtures.Jpeg();
Read(jpeg);
var watch = Stopwatch.StartNew();
for (var i = 0; i < 2000; i++)
{
var m = MetadataReader.Read(new MemoryStream(jpeg, writable: false), "IMG.JPG");
if (m.Width != 4000) Assert.Fail("unexpected width");
}
watch.Stop();
context.Log($"2000 JPEG headers in {watch.ElapsedMilliseconds} ms");
Assert.Less(watch.Elapsed.TotalSeconds, TestTiming.Budget(2.0));
}
[Test]
public void HonoursCancellation()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
Assert.Throws<OperationCanceledException>(() => MetadataReader.Read(new MemoryStream(Fixtures.Nef()), "a.nef", null, cts.Token));
}
[Test]
public void RejectsNonSeekableStreams()
{
Assert.Throws<ArgumentException>(() => MetadataReader.Read(new NonSeekable(), null));
Assert.Throws<ArgumentException>(() => ImageSignature.Detect(new NonSeekable(), null));
}
[Test]
public void ReadsFilesSharedWithAWriter()
{
var path = Path.Combine(context.CreateTempDirectory(), "IMG_0002.JPG");
File.WriteAllBytes(path, JpegBuilder.Minimal(320, 240));
var modified = new DateTime(2021, 6, 7, 8, 9, 10, DateTimeKind.Local);
File.SetLastWriteTime(path, modified);
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
var m = MetadataReader.Read(path);
Assert.Equal((320, 240), (m.Width, m.Height));
Assert.Equal(TimestampSource.FileSystem, m.TimestampSource);
Assert.Equal(new DateTime(2021, 6, 7, 8, 9, 10), m.CapturedAt);
}
}
private static void Check(byte[] bytes, string what)
{
FrameMetadata m;
try
{
m = MetadataReader.Read(new MemoryStream(bytes, writable: false), "fuzz");
}
catch (Exception ex)
{
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}");
return;
}
foreach (var w in m.Warnings)
{
if (w.StartsWith("Parser fault", StringComparison.Ordinal)) Assert.Fail($"{what}: {w}");
}
foreach (var p in m.Previews)
{
if (p.Offset < 0 || p.Length <= 0 || p.Offset + p.Length > bytes.Length) Assert.Fail($"{what}: preview {p} outside the file");
}
if (m.Orientation is < 1 or > 8 || m.Width < 0 || m.Height < 0) Assert.Fail($"{what}: invalid geometry");
}
private sealed class NonSeekable : MemoryStream
{
public override bool CanSeek => false;
}
}
@@ -0,0 +1,196 @@
using System.Text;
using Chronos.Core.Metadata.Tiff;
using Chronos.Core.Metadata.Xmp;
using Chronos.Core.Model;
using Chronos.Core.Tests.Metadata.Builders;
using Chronos.Testing;
using static Chronos.Core.Tests.Metadata.MetadataTestHelpers;
namespace Chronos.Core.Tests.Metadata;
public sealed class XmpTests
{
private const string Head = """<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">""";
private const string Tail = "</rdf:RDF></x:xmpmeta>";
private const string Namespaces = """
xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:exif="http://ns.adobe.com/exif/1.0/"
xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/"
xmlns:aux="http://ns.adobe.com/exif/1.0/aux/" xmlns:exifEX="http://cipa.jp/exif/1.0/"
xmlns:xmpNote="http://ns.adobe.com/xmp/note/"
""";
[Test]
public void ReadsAttributeForm()
{
var v = Parse($"""
{Head}<rdf:Description {Namespaces} xmp:Rating="5" xmp:Label="Green" exif:DateTimeOriginal="2024-03-04T05:06:07.5+01:00"
tiff:Orientation="8" aux:SerialNumber="AUX1" exifEX:BodySerialNumber="BODY1" aux:Lens="AuxLens" exifEX:LensModel="CipaLens"/>{Tail}
""");
Assert.Equal(5, v.Rating);
Assert.Equal("Green", v.Label);
Assert.Equal(new DateTime(2024, 3, 4, 5, 6, 7, 500), v.DateTimeOriginal!.Value.Value);
Assert.Equal(60, v.DateTimeOriginal!.Value.OffsetMinutes);
Assert.Equal(8, v.Orientation);
Assert.Equal("BODY1", v.BodySerial);
Assert.Equal("CipaLens", v.Lens);
}
[Test]
public void ReadsElementForm()
{
var v = Parse($"""
{Head}<rdf:Description {Namespaces}>
<xmp:Rating>-1</xmp:Rating>
<xmp:Label><![CDATA[Purple]]></xmp:Label>
<photoshop:DateCreated>2021-01-02T03:04Z</photoshop:DateCreated>
<xmp:CreateDate>2020-01-01T00:00:00</xmp:CreateDate>
<tiff:Orientation>2</tiff:Orientation>
<aux:SerialNumber>AUX2</aux:SerialNumber>
<aux:Lens><rdf:Alt><rdf:li xml:lang="x-default">Nested Lens</rdf:li></rdf:Alt></aux:Lens>
</rdf:Description>{Tail}
""");
Assert.Equal(-1, v.Rating);
Assert.Equal("Purple", v.Label);
Assert.Equal(new DateTime(2021, 1, 2, 3, 4, 0), v.CaptureTime!.Value.Value);
Assert.Equal(0, v.CaptureTime!.Value.OffsetMinutes);
Assert.Equal(2, v.Orientation);
Assert.Equal("AUX2", v.BodySerial);
Assert.Equal("Nested Lens", v.Lens);
}
[Theory]
[Case("exif:DateTimeOriginal=\"2001-01-01T01:01:01\" photoshop:DateCreated=\"2002-02-02T02:02:02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2001)]
[Case("photoshop:DateCreated=\"2002-02-02T02:02:02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2002)]
[Case("xmp:CreateDate=\"2003-03-03T03:03:03\"", 2003)]
[Case("photoshop:DateCreated=\"2002-02-02\" xmp:CreateDate=\"2003-03-03T03:03:03\"", 2003, Name = "date-only values are not capture times")]
public void CaptureTimeFollowsMwgOrder(string attributes, int year) =>
Assert.Equal(year, Parse($"{Head}<rdf:Description {Namespaces} {attributes}/>{Tail}").CaptureTime!.Value.Value.Year);
[Test]
public void FirstPacketWins()
{
var v = new XmpValues();
Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}<rdf:Description {Namespaces} xmp:Rating=\"2\"/>{Tail}"), v));
Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}<rdf:Description {Namespaces} xmp:Rating=\"5\" xmp:Label=\"Blue\"/>{Tail}"), v));
Assert.Equal(2, v.Rating);
Assert.Equal("Blue", v.Label);
}
[Test]
public void RefusesDtdsAndEntities()
{
var packet = $"""<?xml version="1.0"?><!DOCTYPE x [<!ENTITY e "boom">]>{Head}<rdf:Description {Namespaces} xmp:Label="&e;"/>{Tail}""";
var v = new XmpValues();
var problem = XmpParser.Parse(Encoding.UTF8.GetBytes(packet), v);
Assert.NotNull(problem);
Assert.Null(v.Label);
}
[Test]
public void MalformedPacketKeepsEarlierValues()
{
var v = new XmpValues();
var problem = XmpParser.Parse(Encoding.UTF8.GetBytes($"{Head}<rdf:Description {Namespaces} xmp:Rating=\"3\"><xmp:Label>Yel"), v);
Assert.Contains("Malformed XMP", problem);
Assert.Equal(3, v.Rating);
}
[Test]
public void RejectsPacketsOverFourMegabytes()
{
var packet = new byte[XmpParser.MaxPacketBytes + 1];
packet.AsSpan().Fill((byte)' ');
Assert.Equal("XMP packet larger than 4 MB ignored", XmpParser.Parse(packet, new XmpValues()));
}
[Test]
public void IgnoresTrailingNulPaddingAndInvalidValues()
{
var v = new XmpValues();
var bytes = Encoding.UTF8.GetBytes($"{Head}<rdf:Description {Namespaces} xmp:Rating=\"9\" tiff:Orientation=\"0\" xmp:CreateDate=\"yesterday\"/>{Tail}\0\0\0");
Assert.Null(XmpParser.Parse(bytes, v));
Assert.Null(v.Rating);
Assert.Null(v.Orientation);
Assert.Null(v.CreateDate);
}
[Test]
public void ReassemblesExtendedXmpInJpeg()
{
const string guid = "0123456789ABCDEF0123456789ABCDEF";
var main = $"{Head}<rdf:Description {Namespaces} xmpNote:HasExtendedXMP=\"{guid}\" xmp:Rating=\"1\"/>{Tail}";
var extended = $"{Head}<rdf:Description {Namespaces} xmp:Rating=\"5\" photoshop:DateCreated=\"2019-09-09T09:09:09\" exifEX:LensModel=\"Extended Lens {new string('x', 300)}\"/>{Tail}";
var jpeg = new JpegBuilder().Xmp(main).ExtendedXmp(guid, extended, 200).Build(64, 48);
var m = Read(jpeg);
AssertNoFault(m);
Assert.Equal(1, m.Rating);
Assert.Equal(TimestampSource.Xmp, m.TimestampSource);
Assert.Equal(new DateTime(2019, 9, 9, 9, 9, 9), m.CapturedAt);
Assert.Contains("Extended Lens", m.LensModel);
}
[Test]
public void IgnoresUnreferencedOrIncompleteExtendedXmp()
{
const string guid = "0123456789ABCDEF0123456789ABCDEF";
var extended = $"{Head}<rdf:Description {Namespaces} xmp:Label=\"Ext\"/>{Tail}";
var unreferenced = Read(new JpegBuilder().ExtendedXmp(guid, extended, 64).Build(64, 48));
Assert.Null(unreferenced.Label);
Assert.Contains("Extended XMP present but not referenced by the main packet", unreferenced.Warnings);
var main = $"{Head}<rdf:Description {Namespaces} xmpNote:HasExtendedXMP=\"{guid}\"/>{Tail}";
var builder = new JpegBuilder().Xmp(main).ExtendedXmp(guid, extended, 64);
var bytes = builder.Build(64, 48);
var withoutFirstChunk = Read(RemoveFirstExtendedChunk(bytes));
Assert.Null(withoutFirstChunk.Label);
Assert.Contains("Extended XMP incomplete", withoutFirstChunk.Warnings);
}
[Test]
public void SuppliesSerialAndLensFallbacks()
{
var xmp = $"{Head}<rdf:Description {Namespaces} aux:SerialNumber=\"XMPSN\" aux:Lens=\"XMP Lens\"/>{Tail}";
var exif = Fixtures.ExifIfd(identity: false);
var jpeg = new JpegBuilder().Exif(TiffFile.Build(Fixtures.Ifd0().Child(TiffTags.ExifIfd, exif))).Xmp(xmp).Build(64, 48);
var m = Read(jpeg);
Assert.Equal("XMPSN", m.BodySerial);
Assert.Equal("XMP Lens", m.LensModel);
}
[Test]
public void ExifIdentityBeatsXmp()
{
var xmp = $"{Head}<rdf:Description {Namespaces} aux:SerialNumber=\"XMPSN\" aux:Lens=\"XMP Lens\"/>{Tail}";
var m = Read(new JpegBuilder().Exif(Fixtures.ExifTiff()).Xmp(xmp).Build(64, 48));
Assert.Equal("SN123", m.BodySerial);
Assert.Equal("TestLens 35mm", m.LensModel);
}
[Test]
public void ReadsXmpTagInTiff()
{
var xmp = Encoding.UTF8.GetBytes($"{Head}<rdf:Description {Namespaces} xmp:Label=\"FromTiff\"/>{Tail}");
var tiff = TiffFile.Build(Fixtures.Ifd0().Undefined(TiffTags.Xmp, xmp).Long(TiffTags.ImageWidth, 10).Long(TiffTags.ImageLength, 10));
Assert.Equal("FromTiff", Read(tiff, "a.tif").Label);
}
private static XmpValues Parse(string packet)
{
var values = new XmpValues();
Assert.Null(XmpParser.Parse(Encoding.UTF8.GetBytes(packet), values));
return values;
}
/// <summary>Drops the extended-XMP segment holding offset 0 (written last by <see cref="JpegBuilder.ExtendedXmp"/>).</summary>
private static byte[] RemoveFirstExtendedChunk(byte[] jpeg)
{
var signature = Encoding.ASCII.GetBytes(JpegBuilder.ExtendedXmpSignature);
var last = -1;
for (var i = 0; i + signature.Length < jpeg.Length; i++)
{
if (jpeg.AsSpan(i).StartsWith(signature)) last = i - 4;
}
var length = jpeg[last + 2] << 8 | jpeg[last + 3];
return [.. jpeg.AsSpan(0, last), .. jpeg.AsSpan(last + 2 + length)];
}
}