using Titano.Core.Codecs.Tiff;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Tests.Codecs;
/// Test-side encoders for TIFF compressions the product never writes (LZW, PackBits) and a raw TIFF builder.
internal static class TiffTestEncoders
{
/// TIFF LZW; writes LSB-first codes switching width one code late (pre-6.0 libtiff).
public static byte[] Lzw(ReadOnlySpan data, bool oldStyle = false)
{
var output = new List();
uint acc = 0;
var bits = 0;
var width = 9;
void Put(int code)
{
if (oldStyle)
{
acc |= (uint)code << bits;
bits += width;
while (bits >= 8)
{
output.Add((byte)acc);
acc >>= 8;
bits -= 8;
}
}
else
{
acc = acc << width | (uint)code;
bits += width;
while (bits >= 8)
{
output.Add((byte)(acc >> (bits - 8)));
bits -= 8;
}
}
}
var table = new Dictionary<(int, byte), int>();
var next = 258;
Put(256);
if (data.Length == 0)
{
Put(257);
}
else
{
int current = data[0];
for (var i = 1; i < data.Length; i++)
{
var c = data[i];
if (table.TryGetValue((current, c), out var code))
{
current = code;
continue;
}
Put(current);
table[(current, c)] = next++;
current = c;
if (next == 4094)
{
Put(256);
table.Clear();
next = 258;
width = 9;
}
else if (next >= (1 << width) + (oldStyle ? 1 : 0))
{
width++;
}
}
Put(current);
// libtiff's LZWPostEncode counts the final code too, so EOI uses the decoder's width.
if (++next >= (1 << width) + (oldStyle ? 1 : 0) && width < 12) width++;
Put(257);
}
if (bits > 0) output.Add(oldStyle ? (byte)acc : (byte)(acc << (8 - bits)));
return [.. output];
}
/// PackBits with both literal and replicate runs.
public static byte[] PackBits(ReadOnlySpan data)
{
var output = new List();
var i = 0;
while (i < data.Length)
{
var run = 1;
while (i + run < data.Length && run < 128 && data[i + run] == data[i]) run++;
if (run >= 3)
{
output.Add((byte)(sbyte)(1 - run));
output.Add(data[i]);
i += run;
continue;
}
var start = i;
while (i < data.Length && i - start < 128 && !(i + 2 < data.Length && data[i] == data[i + 1] && data[i] == data[i + 2])) i++;
output.Add((byte)(i - start - 1));
for (var k = start; k < i; k++) output.Add(data[k]);
}
return [.. output];
}
/// Builds a little-endian TIFF from pre-encoded strips or tiles plus layout tags.
public static byte[] Build(Action tags, IReadOnlyList chunks, bool tiled)
{
using var ms = new MemoryStream();
ms.Write("II*\0\0\0\0\0"u8);
var offsets = new uint[chunks.Count];
var counts = new uint[chunks.Count];
for (var i = 0; i < chunks.Count; i++)
{
offsets[i] = (uint)ms.Position;
counts[i] = (uint)chunks[i].Length;
ms.Write(chunks[i]);
if ((ms.Position & 1) != 0) ms.WriteByte(0);
}
var ifd = new TiffDirectory();
tags(ifd);
ifd.Long(tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets, offsets);
ifd.Long(tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts, counts);
TiffWriter.WriteDirectory(ms, 0, ifd);
return ms.ToArray();
}
}