using System.Buffers.Binary;
using System.Text;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
namespace Chronos.Data.Tests.Archiving;
///
/// HEIF files as phones and cameras write them, as far as a host without a HEVC decoder reads them (the server, BRIEF
/// §8.1): the primary image's size (ispe) and an Exif item with the capture time and, in IFD1, a small JPEG
/// thumbnail, the only pixels such a host finds in the file.
///
internal static class HeifFile
{
/// A × HEIF captured at , its Exif
/// thumbnail × (none when the width is 0: such a
/// host finds no pixels in it at all).
public static byte[] Create(DateTime captured, int width, int height, int thumbnailWidth = 160, int thumbnailHeight = 120)
{
var tiff = ExifWriter.BuildTiff(new FrameMetadata { Make = "TestCam", Model = "H-1", CapturedAt = captured });
if (thumbnailWidth > 0)
{
using var small = new ImageBuffer(thumbnailWidth, thumbnailHeight);
for (var c = 0; c < 3; c++) small.Plane(c).Fill(0.2f + c * 0.2f);
tiff = WithThumbnail(tiff, JpegEncoder.Encode(small, new JpegEncodeOptions { Quality = 80 }));
}
byte[] exif = [.. U32(6), .. "Exif\0\0"u8, .. tiff];
// The HEVC-coded primary image, which no managed decoder reads.
var coded = new byte[64];
byte[] Build(int mdat) =>
[
.. Box("ftyp", "heic"u8.ToArray(), U32(0), "mif1heic"u8.ToArray()),
.. FullBox("meta", 0,
FullBox("hdlr", 0, U32(0), "pict"u8.ToArray(), new byte[13]),
FullBox("pitm", 0, U16(1)),
FullBox("iinf", 0, U16(2), FullBox("infe", 2, U16(1), U16(0), "hvc1\0"u8.ToArray()), FullBox("infe", 2, U16(2), U16(0), "Exif\0"u8.ToArray())),
FullBox("iloc", 1, [0x44, 0x00], U16(2),
U16(1), U16(0), U16(0), U16(1), U32(mdat), U32(coded.Length),
U16(2), U16(0), U16(0), U16(1), U32(mdat + coded.Length), U32(exif.Length)),
Box("iprp", Box("ipco", FullBox("ispe", 0, U32(width), U32(height))), FullBox("ipma", 0, U32(1), U16(1), [1, 0x81]))),
];
var head = Build(0);
head = Build(head.Length + 8);
return [.. head, .. Box("mdat", coded, exif)];
}
/// (a single IFD0 chain, as writes it) with an IFD1 holding .
private static byte[] WithThumbnail(byte[] tiff, byte[] thumbnail)
{
const int Entries = 3;
var ifd1 = (tiff.Length + 1) & ~1;
var jpeg = ifd1 + 2 + 12 * Entries + 4;
var result = new byte[jpeg + thumbnail.Length];
tiff.CopyTo(result, 0);
var ifd0Entries = BinaryPrimitives.ReadUInt16LittleEndian(result.AsSpan(8));
BinaryPrimitives.WriteUInt32LittleEndian(result.AsSpan(8 + 2 + 12 * ifd0Entries), (uint)ifd1);
BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(ifd1), Entries);
Entry(result, ifd1 + 2, 0x0103, 3, 6); // Compression: JPEG
Entry(result, ifd1 + 14, 0x0201, 4, (uint)jpeg); // JPEGInterchangeFormat
Entry(result, ifd1 + 26, 0x0202, 4, (uint)thumbnail.Length); // JPEGInterchangeFormatLength
thumbnail.CopyTo(result, jpeg);
return result;
}
/// A little-endian IFD entry with one value.
private static void Entry(byte[] data, int at, ushort tag, ushort type, uint value)
{
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(at), tag);
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(at + 2), type);
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(at + 4), 1);
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(at + 8), value);
}
private static byte[] Box(string type, params byte[][] payload) => [.. U32(8 + payload.Sum(p => p.Length)), .. Encoding.ASCII.GetBytes(type), .. payload.SelectMany(p => p)];
private static byte[] FullBox(string type, byte version, params byte[][] payload) => Box(type, [[version, 0, 0, 0], .. payload]);
private static byte[] U16(int value)
{
var bytes = new byte[2];
BinaryPrimitives.WriteUInt16BigEndian(bytes, (ushort)value);
return bytes;
}
private static byte[] U32(int value)
{
var bytes = new byte[4];
BinaryPrimitives.WriteUInt32BigEndian(bytes, (uint)value);
return bytes;
}
}