using Chronos.Core.Codecs.Gif; using Chronos.Core.Imaging; using Chronos.Testing; namespace Chronos.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"); } } /// Mean absolute difference of 4×4 tile averages. 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 { 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 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; } /// 4×4 blocks coloured from , pattern varying with . 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; } }