using System.Buffers.Binary;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
namespace Chronos.Core.Metadata;
///
/// Identifies a file's format from its leading bytes. TIFF-based files are refined by the CR2 marker, IFD0
/// DNGVersion and Make; ISO-BMFF files by their ftyp brands. The file-name extension only breaks
/// ties between formats that share a container (NEF/NRW, ARW/SRF/SR2, 3FR/FFF, RW2/RWL/RAW, TIFF vs camera RAW).
///
public static class ImageSignature
{
private const int HeadBytes = 32;
private const int MaxFtypBytes = 256;
private static ReadOnlySpan PngSignature => [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A];
private static ReadOnlySpan JpegXrSignature => [(byte)'I', (byte)'I', 0xBC];
private static ReadOnlySpan JpegXlBox => [0, 0, 0, 0x0C, (byte)'J', (byte)'X', (byte)'L', (byte)' ', 0x0D, 0x0A, 0x87, 0x0A];
private static readonly HashSet TiffBasedRaws =
[
ImageFileFormat.Dng, ImageFileFormat.Cr2, ImageFileFormat.Nef, ImageFileFormat.Nrw, ImageFileFormat.Arw,
ImageFileFormat.Srf, ImageFileFormat.Sr2, ImageFileFormat.Orf, ImageFileFormat.Rw2, ImageFileFormat.Raw,
ImageFileFormat.Rwl, ImageFileFormat.Pef, ImageFileFormat.Srw, ImageFileFormat.ThreeFr, ImageFileFormat.Fff,
ImageFileFormat.Iiq, ImageFileFormat.Gpr,
];
/// Detects the format of the bytes in (read from offset 0; the position is restored).
/// Optional name or path whose extension breaks ties; never overrides the signature.
/// when no known signature matches.
public static ImageFileFormat Detect(Stream stream, string? fileName)
{
ArgumentNullException.ThrowIfNull(stream);
if (!stream.CanSeek || !stream.CanRead) throw new ArgumentException("The stream must be readable and seekable.", nameof(stream));
var position = stream.Position;
try
{
var extension = string.IsNullOrEmpty(fileName) ? ImageFileFormat.Unknown : ImageFormatInfo.FromPath(fileName).Format;
return DetectCore(stream, extension);
}
catch (IOException)
{
return ImageFileFormat.Unknown;
}
finally
{
stream.Position = position;
}
}
private static ImageFileFormat DetectCore(Stream stream, ImageFileFormat extension)
{
Span buffer = stackalloc byte[HeadBytes];
var h = buffer[..stream.ReadUpTo(0, buffer)];
if (h.StartsWith((ReadOnlySpan)[0xFF, 0xD8, 0xFF])) return ImageFileFormat.Jpeg;
if (h.StartsWith(PngSignature)) return ImageFileFormat.Png;
if (h.StartsWith("GIF87a"u8) || h.StartsWith("GIF89a"u8)) return ImageFileFormat.Gif;
if (h.StartsWith("FUJIFILMCCD-RAW "u8)) return ImageFileFormat.Raf;
if (h.Length >= 12 && h.StartsWith("RIFF"u8) && h[8..12].SequenceEqual("WEBP"u8)) return ImageFileFormat.WebP;
if (h.StartsWith((ReadOnlySpan)[0xFF, 0x0A]) || h.StartsWith(JpegXlBox)) return ImageFileFormat.JpegXl;
if (h.Length >= 12 && h[4..8].SequenceEqual("ftyp"u8)) return FromBrands(stream, BinaryPrimitives.ReadUInt32BigEndian(h));
if (h.Length >= 4 && h.StartsWith(JpegXrSignature) && h[3] <= 1) return ImageFileFormat.JpegXr;
if (h.Length >= 14 && h[6..14].SequenceEqual("HEAPCCDR"u8)) return ImageFileFormat.Crw;
if (h.StartsWith("IIRO"u8) || h.StartsWith("IIRS"u8) || h.StartsWith("MMOR"u8)) return ImageFileFormat.Orf;
if (h.StartsWith("IIU\0"u8)) return Panasonic(stream, extension);
if (h.StartsWith("II*\0"u8) || h.StartsWith("MM\0*"u8)) return Tiff(stream, h, extension);
if (h.Length >= 18 && h.StartsWith("BM"u8) && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124)
return ImageFileFormat.Bmp;
return ImageFileFormat.Unknown;
}
/// CR3 (crx), AVIF (avif/avis) or HEIF (heic, heix, hevc, hevx, heim, heis, mif1, msf1); major brand first.
private static ImageFileFormat FromBrands(Stream stream, uint ftypSize)
{
Span buffer = stackalloc byte[MaxFtypBytes];
var n = stream.ReadUpTo(0, buffer[..(int)Math.Clamp(ftypSize, 16, MaxFtypBytes)]);
if (n < 12) return ImageFileFormat.Unknown;
var major = Brand(buffer[8..12]);
if (major == BrandKind.Cr3) return ImageFileFormat.Cr3;
if (major == BrandKind.Avif) return ImageFileFormat.Avif;
if (major == BrandKind.Heif) return ImageFileFormat.Heif;
var heif = major == BrandKind.Image;
for (var i = 16; i + 4 <= n; i += 4)
{
var brand = Brand(buffer.Slice(i, 4));
if (brand == BrandKind.Avif) return ImageFileFormat.Avif;
heif |= brand is BrandKind.Heif or BrandKind.Image;
}
return heif ? ImageFileFormat.Heif : ImageFileFormat.Unknown;
}
private enum BrandKind
{
Other,
Cr3,
Avif,
Heif,
Image,
}
private static BrandKind Brand(ReadOnlySpan b) =>
b.SequenceEqual("crx "u8) ? BrandKind.Cr3
: b.SequenceEqual("avif"u8) || b.SequenceEqual("avis"u8) ? BrandKind.Avif
: b.SequenceEqual("heic"u8) || b.SequenceEqual("heix"u8) || b.SequenceEqual("hevc"u8) || b.SequenceEqual("hevx"u8)
|| b.SequenceEqual("heim"u8) || b.SequenceEqual("heis"u8) ? BrandKind.Heif
: b.SequenceEqual("mif1"u8) || b.SequenceEqual("msf1"u8) ? BrandKind.Image
: BrandKind.Other;
private static ImageFileFormat Panasonic(Stream stream, ImageFileFormat extension)
{
if (extension is ImageFileFormat.Rwl or ImageFileFormat.Raw) return extension;
return Make(stream)?.StartsWith("LEICA", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Rwl : ImageFileFormat.Rw2;
}
private static ImageFileFormat Tiff(Stream stream, ReadOnlySpan h, ImageFileFormat extension)
{
if (h.Length >= 10 && h[8..10].SequenceEqual("CR"u8)) return ImageFileFormat.Cr2;
var reader = TiffReader.Open(stream);
var ifd0 = reader?.ReadIfd(reader.FirstIfdOffset);
var make = reader is not null && ifd0 is not null ? IfdValue.String(reader, ifd0, TiffTags.Make) : null;
// A GoPro DNG is GPR only when its raw image is VC-5: one converted by Adobe software (Lightroom, DNG Converter) is
// an ordinary DNG the managed DNG decoder develops (R4, owner review 1).
if (ifd0?.Has(TiffTags.DngVersion) == true)
return extension == ImageFileFormat.Gpr || Codecs.Dng.DngReader.IsVc5(reader!) ? ImageFileFormat.Gpr : ImageFileFormat.Dng;
if (extension == ImageFileFormat.Tiff) return ImageFileFormat.Tiff;
var byMake = ByMake(make, extension);
if (byMake != ImageFileFormat.Unknown) return byMake;
return TiffBasedRaws.Contains(extension) ? extension : ImageFileFormat.Tiff;
}
private static ImageFileFormat ByMake(string? make, ImageFileFormat extension)
{
if (make is null) return ImageFileFormat.Unknown;
bool Is(string prefix) => make.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
if (Is("NIKON")) return extension == ImageFileFormat.Nrw ? ImageFileFormat.Nrw : ImageFileFormat.Nef;
if (Is("SONY")) return extension is ImageFileFormat.Srf or ImageFileFormat.Sr2 ? extension : ImageFileFormat.Arw;
if (Is("PENTAX") || Is("RICOH")) return ImageFileFormat.Pef;
if (Is("SAMSUNG")) return ImageFileFormat.Srw;
if (Is("Hasselblad")) return extension == ImageFileFormat.Fff ? ImageFileFormat.Fff : ImageFileFormat.ThreeFr;
if (Is("Imacon")) return ImageFileFormat.Fff;
if (Is("Phase One") || Is("Leaf")) return ImageFileFormat.Iiq;
return ImageFileFormat.Unknown;
}
private static string? Make(Stream stream)
{
var reader = TiffReader.Open(stream);
return reader?.ReadIfd(reader.FirstIfdOffset) is { } ifd ? IfdValue.String(reader, ifd, TiffTags.Make) : null;
}
}