using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Metadata.Tiff;
using Titano.Core.Metadata.Xmp;
namespace Titano.Core.Metadata.Png;
/// PNG chunks: IHDR (size, bit depth), eXIf (TIFF), iTXt/tEXt "XML:com.adobe.xmp" (XMP, zlib-compressed iTXt
/// supported). Image data chunks are skipped by seeking; CRCs are not verified.
internal static class PngParser
{
private const int MaxChunks = 4096;
private const int KeywordProbeBytes = 80;
private static ReadOnlySpan XmpKeyword => "XML:com.adobe.xmp\0"u8;
public static void Parse(MetadataBuilder m)
{
var s = m.Stream;
Span head = stackalloc byte[8 + 13];
long pos = 8;
for (var i = 0; i < MaxChunks; i++)
{
m.ThrowIfCancelled();
var n = s.ReadUpTo(pos, head);
if (n < 8)
{
m.Warn("PNG truncated before IEND");
return;
}
var length = BinaryPrimitives.ReadUInt32BigEndian(head);
var type = head.Slice(4, 4);
var data = pos + 8;
if (length > int.MaxValue || data > m.Length - length)
{
m.Warn("PNG chunk runs past the end of the file");
return;
}
if (type.SequenceEqual("IHDR"u8) && length >= 13 && n == head.Length)
{
var width = BinaryPrimitives.ReadUInt32BigEndian(head[8..]);
var height = BinaryPrimitives.ReadUInt32BigEndian(head[12..]);
if (width <= int.MaxValue && height <= int.MaxValue) m.SetContainerSize((int)width, (int)height, head[16]);
}
else if (type.SequenceEqual("eXIf"u8) && length >= 8)
{
var exif = n >= 14 && head[8..].StartsWith("Exif\0\0"u8) ? data + 6 : data;
ExifParser.ParseEmbedded(m, exif);
}
else if (type.SequenceEqual("iTXt"u8) || type.SequenceEqual("tEXt"u8))
{
ReadText(m, data, (int)length, international: type[0] == 'i');
}
else if (type.SequenceEqual("IEND"u8))
{
return;
}
pos = data + length + 4;
}
m.Warn("PNG has too many chunks; rest ignored");
}
/// XMP text chunk: keyword "XML:com.adobe.xmp"; iTXt adds compression flag/method, language and translated keyword.
private static void ReadText(MetadataBuilder m, long data, int length, bool international)
{
Span probe = stackalloc byte[XmpKeyword.Length];
if (length < probe.Length || !m.Stream.TryReadAt(data, probe) || !probe.SequenceEqual(XmpKeyword)) return;
if (m.Stream.ReadAt(data, length, XmpParser.MaxPacketBytes + KeywordProbeBytes) is not { } chunk)
{
m.Warn("PNG XMP chunk too large");
return;
}
var r = new SpanReader(chunk);
r.Skip(XmpKeyword.Length);
var compressed = false;
if (international)
{
compressed = r.U8() == 1;
r.Skip(1);
r.CString();
r.CString();
}
if (!r.Ok) return;
var text = chunk.AsMemory(r.Position);
if (!compressed)
{
m.AddXmp(text.ToArray());
return;
}
try
{
using var z = new ZLibStream(new MemoryStream(chunk, r.Position, text.Length, writable: false), CompressionMode.Decompress);
using var packet = new MemoryStream();
var buffer = new byte[16 * 1024];
int read;
while ((read = z.Read(buffer)) > 0)
{
if (packet.Length + read > XmpParser.MaxPacketBytes)
{
m.Warn("PNG XMP larger than 4 MB ignored");
return;
}
packet.Write(buffer, 0, read);
}
m.AddXmp(packet.ToArray());
}
catch (InvalidDataException)
{
m.Warn("PNG compressed XMP is corrupt");
}
}
}