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 == 'é'));
}
/// SOI + APP1 + a minimal 64×48 frame.
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();
for (var i = 0; i < count; i++) tags.Add(BinaryPrimitives.ReadUInt16LittleEndian(reader.ReadRelative(ifd.Position + 2 + 12 * i, 2)!));
Assert.Monotonic(tags, strict: true);
}
}