using System.Globalization;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Metadata.MakerNotes;
///
/// Locates the vendor IFD inside an Exif MakerNote (by header signature, then by camera make) and hands it to the
/// vendor parser. Best effort: unknown layouts are skipped, and every read goes through the bounds-checked
/// .
///
internal static class MakerNoteParser
{
private const int HeaderBytes = 16;
/// Reader of the TIFF block holding the Exif IFD (base and byte order of relative offsets).
/// The Exif 0x927C entry.
public static void Parse(TiffReader exif, IfdEntry makerNote, MetadataBuilder m)
{
if (makerNote.IsInline || makerNote.ByteLength < 14) return;
var start = makerNote.ValuePosition(exif.Base);
if (start < exif.Base || start > m.Length - makerNote.ByteLength)
{
m.Warn("MakerNote outside the file");
return;
}
Span head = stackalloc byte[HeaderBytes];
var h = head[..m.Stream.ReadUpTo(start, head[..(int)Math.Min(HeaderBytes, makerNote.ByteLength)])];
var make = m.Make ?? string.Empty;
var relative = (uint)(start - exif.Base);
if (h.StartsWith("Nikon\0"u8))
{
NikonMakerNote.Parse(exif, start, h, m);
}
else if (h.StartsWith("OLYMPUS\0"u8) || h.StartsWith("OM SYSTEM\0"u8) || h.StartsWith("OLYMP\0"u8))
{
OlympusMakerNote.Parse(exif, start, h, m);
}
else if (h.StartsWith("FUJIFILM"u8))
{
FujifilmMakerNote.Parse(m, start, h);
}
else if (h.StartsWith("Panasonic\0"u8))
{
Vendor(exif, relative + 12, m, PanasonicMakerNote.Parse);
}
else if (h.StartsWith("SONY"u8))
{
Vendor(exif, relative + 12, m, SonyMakerNote.Parse);
}
else if (make.StartsWith("Canon", StringComparison.OrdinalIgnoreCase))
{
Vendor(exif, relative, m, CanonMakerNote.Parse);
}
else if (make.StartsWith("NIKON", StringComparison.OrdinalIgnoreCase))
{
Vendor(exif, relative, m, NikonMakerNote.ParseIfd);
}
else if (make.StartsWith("SONY", StringComparison.OrdinalIgnoreCase))
{
Vendor(exif, relative, m, SonyMakerNote.Parse);
}
}
/// Reads the IFD at a base-relative offset with and runs on it.
internal static void Vendor(TiffReader reader, uint offset, MetadataBuilder m, Action parse)
{
if (reader.ReadIfd(offset) is { } ifd) parse(reader, ifd, m);
else m.Warn("MakerNote IFD unreadable");
}
/// "24-70mm f/2.8", "50mm f/1.8" or "18-55mm F3.5-5.6" from focal-length and aperture ranges.
internal static string FormatLens(double minFocal, double maxFocal, double minAperture, double maxAperture, string aperturePrefix)
{
static string N(double v) => Math.Round(v, 1).ToString("0.#", CultureInfo.InvariantCulture);
var focal = maxFocal > minFocal ? $"{N(minFocal)}-{N(maxFocal)}mm" : $"{N(minFocal)}mm";
if (minAperture <= 0) return focal;
var aperture = maxAperture > minAperture ? $"{N(minAperture)}-{N(maxAperture)}" : N(minAperture);
return $"{focal} {aperturePrefix}{aperture}";
}
}