Files
Chronos/tests/Chronos.Core.Tests/Video/GifEncoderTests.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

256 lines
9.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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");
}
}
/// <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;
}
}