feat(gif): add animated GIF encoder with variance-split palettes, dithering and frame differencing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:49:30 +00:00
1 parent e15bbb9974
commit 71c0113f5f
5 files changed
+1166

No files matched your search

@@ -0,0 +1,255 @@
using Titano.Core.Codecs.Gif;
using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Video;
public sealed class GifEncoderTests(TestContext context)
{
private const int W = 64, H = 48;
private const long Frame30 = 3000; // 1/30 s in 90 kHz ticks
[Test]
public void SmoothFramesRoundTripWithinPaletteError()
{
var frames = Enumerable.Range(0, 4).Select(i => Smooth(i * 3)).ToList();
var plain = Encode(frames, new GifEncoderOptions { Dither = false });
var dithered = Encode(frames, new GifEncoderOptions());
Assert.Equal(4, plain.Frames.Count);
Assert.True(plain.GlobalTable);
for (var f = 0; f < frames.Count; f++)
{
var (mean, max) = Error(frames[f], plain.Frames[f].Canvas);
Assert.Less(mean, 6.0, $"frame {f} mean error");
Assert.Less(max, 40, $"frame {f} max error");
context.Log($"frame {f}: plain {mean:0.00}/{max}, dithered tiles {TileError(frames[f], dithered.Frames[f].Canvas):0.00}");
// Dithering trades per-pixel error for accurate local averages.
Assert.Less(TileError(frames[f], dithered.Frames[f].Canvas), 2.0, $"frame {f} 4×4 average error");
}
}
/// <summary>Mean absolute difference of 4×4 tile averages.</summary>
private static double TileError(byte[] rgb, byte[] rgba)
{
double sum = 0;
var tiles = 0;
for (var ty = 0; ty < H / 4; ty++)
{
for (var tx = 0; tx < W / 4; tx++)
{
for (var c = 0; c < 3; c++)
{
double a = 0, b = 0;
for (var y = 0; y < 4; y++)
{
for (var x = 0; x < 4; x++)
{
var i = (ty * 4 + y) * W + tx * 4 + x;
a += rgb[i * 3 + c];
b += rgba[i * 4 + c];
}
}
sum += Math.Abs(a - b) / 16;
tiles++;
}
}
}
return sum / tiles;
}
[Test]
public void ExactColoursReproduceExactly()
{
var palette = RandomColours(120, 5);
var frames = Enumerable.Range(0, 3).Select(i => Blocks(palette, i)).ToList();
var gif = Encode(frames, new GifEncoderOptions { Dither = false, DifferenceThreshold = 0 });
for (var f = 0; f < frames.Count; f++) Assert.Equal((0.0, 0), Error(frames[f], gif.Frames[f].Canvas));
}
[Test]
public void DelaysFollowTheCumulativeTimelineAndLoopIsWritten()
{
var frames = Enumerable.Range(0, 10).Select(i => Blocks(RandomColours(8, i), i)).ToList();
var gif = Encode(frames, new GifEncoderOptions());
Assert.Equal(0, gif.LoopCount);
Assert.SequenceEqual([3, 4, 3, 3, 4, 3, 3, 4, 3, 3], gif.Frames.Select(f => f.DelayCs));
Assert.Equal(33, gif.Frames.Sum(f => f.DelayCs));
Assert.Equal(5, Encode(frames, new GifEncoderOptions { LoopCount = 5 }).LoopCount);
Assert.Null(Encode(frames, new GifEncoderOptions { LoopCount = null }).LoopCount);
}
[Test]
public void DifferencingCropsToTheChangedAreaAndKeepsTheRest()
{
var palette = RandomColours(64, 9);
var a = Blocks(palette, 0);
var b = (byte[])a.Clone();
for (var y = 7; y < 11; y++)
{
for (var x = 10; x < 15; x++)
{
var i = (y * W + x) * 3;
b[i] = (byte)(255 - b[i]);
b[i + 1] = (byte)(255 - b[i + 1]);
}
}
var gif = Encode([a, b], new GifEncoderOptions { Dither = false, DifferenceThreshold = 0 });
Assert.Equal(2, gif.Frames.Count);
var second = gif.Frames[1];
Assert.Equal((10, 7, 5, 4), (second.Left, second.Top, second.Width, second.Height));
Assert.True(second.Transparent);
Assert.Equal(1, second.Disposal);
Assert.Equal(1, gif.Frames[0].Disposal);
Assert.False(gif.Frames[0].Transparent);
Assert.Equal((0.0, 0), Error(b, second.Canvas));
}
[Test]
public void IdenticalFramesMergeIntoOneLongerFrame()
{
var palette = RandomColours(16, 2);
var a = Blocks(palette, 0);
var b = Blocks(palette, 1);
var gif = Encode([a, a, a, b], new GifEncoderOptions { Dither = false });
Assert.Equal(2, gif.Frames.Count);
Assert.Equal(10, gif.Frames[0].DelayCs);
Assert.Equal(3, gif.Frames[1].DelayCs);
}
[Test]
public void LocalPalettesFollowEachFrame()
{
var reds = Enumerable.Range(0, 200).SelectMany(i => new[] { (byte)(55 + i), (byte)(i / 4), (byte)0 }).ToArray();
var blues = Enumerable.Range(0, 200).SelectMany(i => new[] { (byte)0, (byte)(i / 4), (byte)(55 + i) }).ToArray();
var frames = new List<byte[]> { Blocks(reds, 0), Blocks(blues, 0) };
var gif = Encode(frames, new GifEncoderOptions { PaletteMode = GifPaletteMode.Local, Dither = false, DifferenceThreshold = 0 });
Assert.False(gif.GlobalTable);
Assert.True(gif.Frames.All(f => f.LocalTable));
for (var f = 0; f < 2; f++) Assert.Equal((0.0, 0), Error(frames[f], gif.Frames[f].Canvas));
}
[Test]
public void LzwSurvivesDictionaryResets()
{
// 200×200 pixels of random indices fill the 4096-entry dictionary many times over.
const int size = 200;
var palette = RandomColours(200, 4);
var rng = new Random(8);
var rgb = new byte[size * size * 3];
for (var i = 0; i < size * size; i++)
{
var c = rng.Next(200);
rgb[i * 3] = palette[c * 3];
rgb[i * 3 + 1] = palette[c * 3 + 1];
rgb[i * 3 + 2] = palette[c * 3 + 2];
}
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, size, size, new GifEncoderOptions { Dither = false, FrameDifferencing = false });
encoder.AddFrame(rgb, Frame30);
encoder.Complete();
var gif = GifTestDecoder.Decode(ms.ToArray());
Assert.Equal((0.0, 0), Error(rgb, gif.Frames[0].Canvas));
}
[Test]
public void LinearImageBuffersAreEncodedAsSrgb()
{
var palette = RandomColours(30, 6);
var rgb = Blocks(palette, 3);
using var image = new ImageBuffer(W, H);
for (var i = 0; i < W * H; i++)
{
for (var c = 0; c < 3; c++) image.Plane(c)[i] = ColorSpace.Linear8(rgb[i * 3 + c]);
}
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, W, H, new GifEncoderOptions { Dither = false });
encoder.AddFrame(image, Frame30);
encoder.Complete();
Assert.Equal(1, encoder.FrameCount);
Assert.Equal((0.0, 0), Error(rgb, GifTestDecoder.Decode(ms.ToArray()).Frames[0].Canvas));
}
[Test]
public void SuppliedPaletteIsUsedAsGlobalTable()
{
using var image = new ImageBuffer(W, H);
image.Plane(0).Fill(0.5f);
var palette = GifEncoder.BuildPalette([image], 4);
Assert.Equal(3, palette.Length);
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, W, H, new GifEncoderOptions { Palette = palette });
encoder.AddFrame(image, Frame30);
encoder.Complete();
var gif = GifTestDecoder.Decode(ms.ToArray());
Assert.True(gif.GlobalTable);
Assert.Equal(ColorSpace.Encode8(0.5f), gif.Frames[0].Canvas[0]);
}
private static GifTestDecoder Encode(List<byte[]> frames, GifEncoderOptions options)
{
using var ms = new MemoryStream();
var encoder = new GifEncoder(ms, W, H, options);
foreach (var f in frames) encoder.AddFrame(f, Frame30);
encoder.Complete();
return GifTestDecoder.Decode(ms.ToArray());
}
private static (double Mean, int Max) Error(byte[] rgb, byte[] rgba)
{
long sum = 0;
var max = 0;
for (var i = 0; i < rgb.Length / 3; i++)
{
for (var c = 0; c < 3; c++)
{
var d = Math.Abs(rgb[i * 3 + c] - rgba[i * 4 + c]);
sum += d;
max = Math.Max(max, d);
}
}
return (sum / (double)rgb.Length, max);
}
private static byte[] Smooth(int shift)
{
var rgb = new byte[W * H * 3];
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
var i = (y * W + x) * 3;
rgb[i] = (byte)((x + shift) * 255 / (W + 12));
rgb[i + 1] = (byte)(y * 255 / H);
rgb[i + 2] = (byte)(128 + 100 * Math.Sin((x + y + shift) * 0.1));
}
}
return rgb;
}
private static byte[] RandomColours(int count, int seed)
{
var bytes = new byte[count * 3];
new Random(seed).NextBytes(bytes);
return bytes;
}
/// <summary>4×4 blocks coloured from <paramref name="palette"/>, pattern varying with <paramref name="variant"/>.</summary>
private static byte[] Blocks(byte[] palette, int variant)
{
var colours = palette.Length / 3;
var rgb = new byte[W * H * 3];
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
var c = ((x / 4) * 7 + (y / 4) * 13 + variant * 5) % colours;
var i = (y * W + x) * 3;
rgb[i] = palette[c * 3];
rgb[i + 1] = palette[c * 3 + 1];
rgb[i + 2] = palette[c * 3 + 2];
}
}
return rgb;
}
}
@@ -0,0 +1,197 @@
using System.Text;
using Titano.Testing;
namespace Titano.Core.Tests.Video;
/// <summary>Minimal GIF89a decoder used to verify <c>GifEncoder</c> output (composition with disposal 0–3).</summary>
internal sealed class GifTestDecoder
{
public sealed record Frame(byte[] Canvas, int DelayCs, int Left, int Top, int Width, int Height, int Disposal, bool Transparent, bool LocalTable);
public int Width { get; private set; }
public int Height { get; private set; }
public bool GlobalTable { get; private set; }
public int? LoopCount { get; private set; }
public List<Frame> Frames { get; } = [];
public static GifTestDecoder Decode(byte[] data)
{
var gif = new GifTestDecoder();
Assert.Equal("GIF89a", Encoding.ASCII.GetString(data, 0, 6));
gif.Width = data[6] | data[7] << 8;
gif.Height = data[8] | data[9] << 8;
var pos = 13;
byte[]? global = null;
if ((data[10] & 0x80) != 0)
{
gif.GlobalTable = true;
var size = 3 << ((data[10] & 7) + 1);
global = data.AsSpan(pos, size).ToArray();
pos += size;
}
var canvas = new byte[gif.Width * gif.Height * 4];
int delay = 0, disposal = 0, transparentIndex = -1;
while (true)
{
var block = data[pos++];
if (block == 0x3B) break;
if (block == 0x21)
{
var label = data[pos++];
if (label == 0xF9)
{
Assert.Equal((byte)4, data[pos]);
disposal = (data[pos + 1] >> 2) & 7;
transparentIndex = (data[pos + 1] & 1) != 0 ? data[pos + 4] : -1;
delay = data[pos + 2] | data[pos + 3] << 8;
pos += 6;
}
else if (label == 0xFF && Encoding.ASCII.GetString(data, pos + 1, 11) == "NETSCAPE2.0")
{
gif.LoopCount = data[pos + 14] | data[pos + 15] << 8;
pos += 12;
pos = SkipSubBlocks(data, pos);
}
else
{
pos = SkipSubBlocks(data, pos);
}
continue;
}
Assert.Equal((byte)0x2C, block);
var left = data[pos] | data[pos + 1] << 8;
var top = data[pos + 2] | data[pos + 3] << 8;
var w = data[pos + 4] | data[pos + 5] << 8;
var h = data[pos + 6] | data[pos + 7] << 8;
var packed = data[pos + 8];
pos += 9;
var table = global;
var local = (packed & 0x80) != 0;
if (local)
{
var size = 3 << ((packed & 7) + 1);
table = data.AsSpan(pos, size).ToArray();
pos += size;
}
Assert.False((packed & 0x40) != 0, "interlaced frames are not produced");
Assert.True(left + w <= gif.Width && top + h <= gif.Height, "frame inside the logical screen");
var minCode = data[pos++];
using var lzw = new MemoryStream();
while (data[pos] != 0)
{
lzw.Write(data, pos + 1, data[pos]);
pos += data[pos] + 1;
}
pos++;
var indices = DecodeLzw(lzw.ToArray(), minCode, w * h);
var saved = disposal == 3 ? (byte[])canvas.Clone() : null;
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
var index = indices[y * w + x];
if (index == transparentIndex) continue;
var o = ((top + y) * gif.Width + left + x) * 4;
canvas[o] = table![index * 3];
canvas[o + 1] = table[index * 3 + 1];
canvas[o + 2] = table[index * 3 + 2];
canvas[o + 3] = 255;
}
}
gif.Frames.Add(new Frame((byte[])canvas.Clone(), delay, left, top, w, h, disposal, transparentIndex >= 0, local));
if (disposal == 2)
{
for (var y = 0; y < h; y++) canvas.AsSpan(((top + y) * gif.Width + left) * 4, w * 4).Clear();
}
else if (disposal == 3)
{
canvas = saved!;
}
delay = 0;
disposal = 0;
transparentIndex = -1;
}
return gif;
}
private static int SkipSubBlocks(byte[] data, int pos)
{
while (data[pos] != 0) pos += data[pos] + 1;
return pos + 1;
}
private static byte[] DecodeLzw(byte[] data, int minCode, int pixels)
{
var output = new List<byte>(pixels);
var prefix = new short[4096];
var suffix = new byte[4096];
var stack = new byte[4097];
var clear = 1 << minCode;
var end = clear + 1;
var codeSize = minCode + 1;
var next = end + 1;
var old = -1;
long bits = 0;
var count = 0;
var pos = 0;
while (true)
{
while (count < codeSize && pos < data.Length)
{
bits |= (long)data[pos++] << count;
count += 8;
}
Assert.True(count >= codeSize, "LZW data ended before the end code");
var code = (int)(bits & ((1 << codeSize) - 1));
bits >>= codeSize;
count -= codeSize;
if (code == clear)
{
codeSize = minCode + 1;
next = end + 1;
old = -1;
continue;
}
if (code == end) break;
if (old == -1)
{
Assert.True(code < clear, "first code after clear is a literal");
output.Add((byte)code);
old = code;
continue;
}
Assert.True(code <= next, $"LZW code {code} beyond the table ({next})");
var depth = 0;
var c = code;
if (code == next)
{
stack[depth++] = First(old, prefix, suffix, clear);
c = old;
}
while (c >= clear)
{
stack[depth++] = suffix[c];
c = prefix[c];
}
stack[depth++] = (byte)c;
var firstByte = (byte)c;
for (var i = depth - 1; i >= 0; i--) output.Add(stack[i]);
if (next < 4096)
{
prefix[next] = (short)old;
suffix[next] = firstByte;
next++;
if (next == 1 << codeSize && codeSize < 12) codeSize++;
}
old = code;
}
Assert.Equal(pixels, output.Count);
return [.. output];
}
private static byte First(int code, short[] prefix, byte[] suffix, int clear)
{
while (code >= clear) code = prefix[code];
return (byte)code;
}
}