refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

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. 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) and
  pe-check.

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,167 @@
using System.Text;
using Chronos.Testing;
namespace Chronos.Core.Tests.Codecs;
/// <summary>Shared fixtures, synthetic images and image metrics for codec tests.</summary>
internal static class CodecTestData
{
public static byte[] Fixture(string relativePath) =>
File.ReadAllBytes(Path.Combine(TestContext.FixturesDirectory, "codecs", relativePath));
/// <summary>Netpbm P5/P6/P7 (PAM) reader for reference images; samples are big-endian when maxval &gt; 255.</summary>
public static Pnm ReadPnm(byte[] data)
{
var pos = 0;
string Token()
{
while (pos < data.Length && (char.IsWhiteSpace((char)data[pos]) || data[pos] == '#'))
{
if (data[pos] == '#') while (pos < data.Length && data[pos] != '\n') pos++;
else pos++;
}
var start = pos;
while (pos < data.Length && !char.IsWhiteSpace((char)data[pos])) pos++;
return Encoding.ASCII.GetString(data, start, pos - start);
}
var magic = Token();
int width, height, channels, maxVal;
if (magic == "P7")
{
width = height = channels = maxVal = 0;
for (var t = Token(); t != "ENDHDR"; t = Token())
{
switch (t)
{
case "WIDTH": width = int.Parse(Token()); break;
case "HEIGHT": height = int.Parse(Token()); break;
case "DEPTH": channels = int.Parse(Token()); break;
case "MAXVAL": maxVal = int.Parse(Token()); break;
case "TUPLTYPE": Token(); break;
}
}
}
else
{
channels = magic switch { "P5" => 1, "P6" => 3, _ => throw new InvalidDataException(magic) };
width = int.Parse(Token());
height = int.Parse(Token());
maxVal = int.Parse(Token());
}
pos++;
var samples = new int[width * height * channels];
for (var i = 0; i < samples.Length; i++)
{
samples[i] = maxVal > 255 ? data[pos + 2 * i] << 8 | data[pos + 2 * i + 1] : data[pos + i];
}
return new Pnm(width, height, channels, maxVal, samples);
}
public sealed record Pnm(int Width, int Height, int Channels, int MaxVal, int[] Samples)
{
public byte[] Bytes => Samples.Select(s => (byte)s).ToArray();
public ushort[] Words => Samples.Select(s => (ushort)s).ToArray();
}
/// <summary>Deterministic RGB test card: smooth gradients, saturated colour bars, seeded noise and
/// text-like one-pixel strokes (the four content classes codecs struggle with).</summary>
public static byte[] TestCard(int width, int height, int seed = 1)
{
var rng = new Random(seed);
var rgb = new byte[width * height * 3];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var band = y * 4 / height;
int r, g, b;
switch (band)
{
case 0:
r = x * 255 / Math.Max(1, width - 1);
g = y * 4 * 255 / Math.Max(1, height - 1) / 4 * 4 % 256;
b = 255 - r;
break;
case 1:
var bar = x * 8 / width;
r = (bar & 4) != 0 ? 230 : 25;
g = (bar & 2) != 0 ? 230 : 25;
b = (bar & 1) != 0 ? 230 : 25;
break;
case 2:
r = rng.Next(256);
g = rng.Next(256);
b = rng.Next(256);
break;
default:
var stroke = x % 7 == 0 || y % 9 == 0 || (x + y) % 13 == 0;
r = g = b = stroke ? 20 : 235;
break;
}
var i = (y * width + x) * 3;
rgb[i] = (byte)r;
rgb[i + 1] = (byte)g;
rgb[i + 2] = (byte)b;
}
}
return rgb;
}
/// <summary>Smooth photographic-like content (low-frequency gradients); compresses like real photos.</summary>
public static byte[] SmoothImage(int width, int height)
{
var rgb = new byte[width * height * 3];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
double u = x / (double)width, v = y / (double)height;
var i = (y * width + x) * 3;
rgb[i] = (byte)(127.5 + 120 * Math.Sin(6.1 * u + 2.3 * v));
rgb[i + 1] = (byte)(127.5 + 120 * Math.Cos(4.7 * u * v + 3.1 * v));
rgb[i + 2] = (byte)(127.5 + 120 * Math.Sin(9.3 * v - 1.7 * u + 0.5));
}
}
return rgb;
}
public static double Psnr(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b) => Psnr(a, b, 255);
public static double Psnr<T>(ReadOnlySpan<T> a, ReadOnlySpan<T> b, double peak) where T : struct, IConvertible
{
Assert.Equal(a.Length, b.Length, "sample count");
double sum = 0;
for (var i = 0; i < a.Length; i++)
{
var d = a[i].ToDouble(null) - b[i].ToDouble(null);
sum += d * d;
}
var mse = sum / a.Length;
return mse == 0 ? 99 : 10 * Math.Log10(peak * peak / mse);
}
public static int MaxAbsDiff(ReadOnlySpan<byte> a, ReadOnlySpan<int> b)
{
Assert.Equal(a.Length, b.Length, "sample count");
var max = 0;
for (var i = 0; i < a.Length; i++) max = Math.Max(max, Math.Abs(a[i] - b[i]));
return max;
}
/// <summary>Seeded corruption: the input truncated at <paramref name="cases"/> points plus single-byte flips.</summary>
public static IEnumerable<byte[]> Corruptions(byte[] valid, int cases, int seed)
{
var rng = new Random(seed);
for (var i = 0; i < cases; i++)
{
yield return valid.AsSpan(0, rng.Next(valid.Length)).ToArray();
var flipped = (byte[])valid.Clone();
var flips = 1 + rng.Next(4);
for (var f = 0; f < flips; f++) flipped[rng.Next(flipped.Length)] ^= (byte)(1 << rng.Next(8));
yield return flipped;
var garbage = (byte[])valid.Clone();
garbage[rng.Next(garbage.Length)] = (byte)rng.Next(256);
yield return garbage;
}
}
}
@@ -0,0 +1,79 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Testing;
using static Chronos.Core.Tests.Codecs.CodecTestData;
namespace Chronos.Core.Tests.Codecs;
/// <summary>Decoder output against libjpeg-turbo's djpeg (accurate integer IDCT) on cjpeg-produced fixtures.</summary>
public sealed class JpegDecoderTests(TestContext context)
{
[Theory]
[Case("b444", "4:4:4")]
[Case("b422", "4:2:2")]
[Case("b420", "4:2:0")]
[Case("b440", "4:4:0")]
[Case("b411", "4:1:1")]
[Case("p420", "4:2:0")]
[Case("p444", "4:4:4")]
[Case("r420", "4:2:0")]
[Case("r444", "4:4:4")]
public void MatchesDjpeg(string name, string sampling)
{
var data = Fixture($"jpeg/{name}.jpg");
var reference = ReadPnm(Fixture($"jpeg/{name}.ppm"));
var image = JpegDecoder.Decode(data);
Assert.Equal(reference.Width, image.Width);
Assert.Equal(reference.Height, image.Height);
Assert.Equal(3, image.Components);
Assert.Equal(sampling, image.Info.SamplingNotation);
Assert.Empty(image.Warnings);
var diff = MaxAbsDiff(image.Pixels8, reference.Samples);
context.Log($"{name}: max |diff| = {diff}");
Assert.LessOrEqual(diff, 2);
}
[Theory]
[Case("gray")]
[Case("pgray")]
public void GrayMatchesDjpeg(string name)
{
var image = JpegDecoder.Decode(Fixture($"jpeg/{name}.jpg"));
var reference = ReadPnm(Fixture($"jpeg/{name}.pgm"));
Assert.Equal(1, image.Components);
Assert.Equal(JpegColorSpace.Gray, image.Info.ColorSpace);
Assert.LessOrEqual(MaxAbsDiff(image.Pixels8, reference.Samples), 2);
}
[Test]
public void ReplicatedUpsamplingMatchesDjpegNoSmooth()
{
var image = JpegDecoder.Decode(Fixture("jpeg/b420.jpg"), new JpegDecodeOptions { FancyUpsampling = false });
Assert.LessOrEqual(MaxAbsDiff(image.Pixels8, ReadPnm(Fixture("jpeg/b420-nosmooth.ppm")).Samples), 2);
}
[Test]
public void ReadInfoParsesHeadersOnly()
{
var info = JpegDecoder.ReadInfo(Fixture("jpeg/p420.jpg"));
Assert.Equal(61, info.Width);
Assert.Equal(45, info.Height);
Assert.Equal(JpegProcess.Progressive, info.Process);
Assert.Equal(JpegColorSpace.YCbCr, info.ColorSpace);
Assert.Equal(8, info.Precision);
var restart = JpegDecoder.ReadInfo(Fixture("jpeg/r444.jpg"));
Assert.Equal(5, restart.RestartInterval);
}
[Test]
public void AdobeYcckIsConvertedToRgb()
{
var image = JpegDecoder.Decode(Fixture("jpeg/cmyk.jpg"));
Assert.Equal(JpegColorSpace.Ycck, image.Info.ColorSpace);
Assert.Equal(4, image.Info.Components);
Assert.Equal(3, image.Components);
var source = ReadPnm(Fixture("src.ppm"));
var psnr = Psnr(image.Pixels8, source.Bytes);
context.Log($"YCCK round trip PSNR {psnr:F1} dB");
Assert.Greater(psnr, 30);
}
}
@@ -0,0 +1,309 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Testing;
using static Chronos.Core.Tests.Codecs.CodecTestData;
namespace Chronos.Core.Tests.Codecs;
/// <summary>Encoder → decoder round trips on synthetic content.</summary>
public sealed class JpegEncoderTests(TestContext context)
{
private const int W = 160, H = 120;
/// <summary>The four synthetic content classes: smooth gradients, colour bars, sensor-like noise, text-like edges.</summary>
private static byte[] Content(string kind)
{
var rgb = new byte[W * H * 3];
var rng = new Random(11);
for (var y = 0; y < H; y++)
{
for (var x = 0; x < W; x++)
{
int r, g, b;
switch (kind)
{
case "gradients":
r = x * 255 / (W - 1);
g = y * 255 / (H - 1);
b = (x + y) * 255 / (W + H - 2);
break;
case "bars":
var bar = x / (W / 8);
r = (bar & 4) != 0 ? 235 : 16;
g = (bar & 2) != 0 ? 235 : 16;
b = (bar & 1) != 0 ? 235 : 16;
break;
case "noise":
// Sensor-like: mostly luma noise (σ ≈ 3.7 levels) plus weak chroma noise.
var n = rng.Next(-6, 7);
r = 120 + x / 4 + n + rng.Next(-2, 3);
g = 110 + y / 4 + n + rng.Next(-2, 3);
b = 100 + n + rng.Next(-2, 3);
break;
default:
var ink = (x % 11 is 2 or 3 && y % 16 < 12) || (y % 16 is 5 && x % 11 < 8);
r = g = b = ink ? 24 : 232;
break;
}
var i = (y * W + x) * 3;
rgb[i] = (byte)r;
rgb[i + 1] = (byte)g;
rgb[i + 2] = (byte)b;
}
}
return rgb;
}
private static double RoundTripPsnr(byte[] rgb, JpegEncodeOptions options, int channels = 3)
{
var jpeg = JpegEncoder.Encode(rgb, W, H, channels, options);
var decoded = JpegDecoder.Decode(jpeg);
return Psnr(decoded.Pixels8, rgb);
}
/// <summary>PSNR of Rec.601 luma (Y′). 4:2:0 halves chroma resolution by design, so saturated chroma edges
/// (colour bars) lose a quarter of the step under triangle upsampling in any codec (libjpeg: 26.7 dB RGB on
/// the same bars); the codec's own fidelity is measured on Y′.</summary>
private static double RoundTripLumaPsnr(byte[] rgb, JpegEncodeOptions options)
{
var decoded = JpegDecoder.Decode(JpegEncoder.Encode(rgb, W, H, 3, options)).Pixels8!;
static double[] Luma(byte[] p)
{
var y = new double[p.Length / 3];
for (var i = 0; i < y.Length; i++) y[i] = 0.299 * p[3 * i] + 0.587 * p[3 * i + 1] + 0.114 * p[3 * i + 2];
return y;
}
return Psnr<double>(Luma(decoded), Luma(rgb), 255);
}
[Theory]
[Case("gradients")]
[Case("bars")]
[Case("noise")]
[Case("text")]
public void HighQuality444Above40Db(string kind)
{
var psnr = RoundTripPsnr(Content(kind), new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444 });
context.Log($"{kind} q95 4:4:4: {psnr:F2} dB");
Assert.GreaterOrEqual(psnr, 40);
}
[Theory]
[Case("gradients")]
[Case("bars")]
[Case("noise")]
[Case("text")]
public void Quality90Yuv420Above34Db(string kind)
{
var options = new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 };
var psnr = RoundTripLumaPsnr(Content(kind), options);
context.Log($"{kind} q90 4:2:0: Y′ {psnr:F2} dB, RGB {RoundTripPsnr(Content(kind), options):F2} dB");
Assert.GreaterOrEqual(psnr, 34);
}
[Test]
public void PsnrAndSizeGrowWithQuality()
{
var rgb = TestCard(W, H);
var psnr = new List<double>();
var sizes = new List<double>();
foreach (var q in new[] { 5, 20, 40, 60, 75, 85, 95, 100 })
{
var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = q, Subsampling = JpegSubsampling.Yuv422 });
sizes.Add(jpeg.Length);
psnr.Add(Psnr(JpegDecoder.Decode(jpeg).Pixels8, rgb));
}
context.Log("PSNR: " + string.Join(", ", psnr.Select(p => p.ToString("F1"))));
Assert.Monotonic(psnr, strict: true);
Assert.Monotonic(sizes, strict: true);
}
[Test]
public void OptimizedHuffmanIsSmallerAndPixelIdentical()
{
var rgb = TestCard(W, H);
var standard = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 85 });
var optimized = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 85, OptimizeHuffman = true });
context.Log($"standard {standard.Length} B, optimized {optimized.Length} B");
Assert.Less(optimized.Length, standard.Length);
Assert.BytesEqual(JpegDecoder.Decode(standard).Pixels8, JpegDecoder.Decode(optimized).Pixels8);
}
[Theory]
[Case(1)]
[Case(7)]
[Case(40)]
public void RestartIntervalsDecodeIdentically(int interval)
{
var rgb = TestCard(W, H);
var plain = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 80 });
var restart = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 80, RestartInterval = interval, OptimizeHuffman = true });
Assert.Equal(interval, JpegDecoder.ReadInfo(restart).RestartInterval);
var decoded = JpegDecoder.Decode(restart);
Assert.Empty(decoded.Warnings);
Assert.BytesEqual(JpegDecoder.Decode(plain).Pixels8, decoded.Pixels8);
}
[Test]
public void App1SegmentsFollowSoiAndReplaceJfif()
{
var exif = "Exif\0\0II*\0\b\0\0\0\0\0\0\0"u8.ToArray();
var xmp = "http://ns.adobe.com/xap/1.0/\0<x:xmpmeta/>"u8.ToArray();
var jpeg = JpegEncoder.Encode(TestCard(32, 16), 32, 16, 3, new JpegEncodeOptions { App1Segments = [exif, xmp] });
Assert.Equal(0xE1, jpeg[3]);
Assert.BytesEqual(exif, jpeg.AsSpan(6, exif.Length));
var second = 4 + (jpeg[4] << 8 | jpeg[5]);
Assert.Equal(0xE1, jpeg[second + 1]);
Assert.False(jpeg.AsSpan().IndexOf("JFIF"u8) >= 0, "JFIF must be omitted when APP1 is supplied");
Assert.Equal(32, JpegDecoder.Decode(jpeg).Width);
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(TestCard(8, 8), 8, 8, 3, new JpegEncodeOptions { App1Segments = [new byte[65534]] }));
}
[Test]
public void GrayBufferEncodesSingleComponent()
{
using var gray = new ImageBuffer(50, 30, 1);
for (var i = 0; i < gray.PlaneLength; i++) gray.Plane(0)[i] = (i % 50) / 49f;
var jpeg = JpegEncoder.Encode(gray, new JpegEncodeOptions { Quality = 95 });
var info = JpegDecoder.ReadInfo(jpeg);
Assert.Equal(1, info.Components);
using var back = JpegDecoder.DecodeToLinear(jpeg);
Assert.Equal(1, back.Channels);
for (var x = 0; x < 50; x += 7) Assert.Approximately(gray[0, x, 15], back[0, x, 15], 0.02);
}
[Test]
public void LinearBufferRoundTripWithDither()
{
using var image = new ImageBuffer(96, 64);
for (var y = 0; y < 64; y++)
{
for (var x = 0; x < 96; x++)
{
image[0, x, y] = x / 95f;
image[1, x, y] = y / 63f * 0.5f;
image[2, x, y] = 0.18f;
}
}
var jpeg = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444, Dither = true });
using var back = JpegDecoder.DecodeToLinear(jpeg);
var reference = PixelConvert.ToInterleaved8(image, 3);
var decoded = PixelConvert.ToInterleaved8(back, 3);
var psnr = Psnr(decoded, reference);
context.Log($"linear round trip {psnr:F1} dB");
Assert.Greater(psnr, 40);
}
[Test]
public void TwelveBitExtendedSequentialDecodes()
{
const int w = 40, h = 24;
var samples = new ushort[w * h];
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++) samples[y * w + x] = (ushort)(x * 4095 / (w - 1) ^ (y * 37 % 256));
}
var jpeg = TwelveBitEncoder.EncodeGray(samples, w, h);
var image = JpegDecoder.Decode(jpeg);
Assert.Equal(12, image.BitDepth);
Assert.Equal(JpegProcess.ExtendedSequential, image.Info.Process);
var psnr = Psnr<ushort>(image.Pixels16, samples, 4095);
context.Log($"12-bit PSNR {psnr:F1} dB");
Assert.Greater(psnr, 50);
using var linear = JpegDecoder.DecodeToLinear(jpeg);
Assert.Approximately(ColorSpace.SrgbToLinear(image.Pixels16![5] / 4095.0), linear[0, 5, 0], 1e-4);
}
/// <summary>Minimal SOF1 12-bit gray encoder (quantiser 1, optimal tables) for decoder tests.</summary>
private static class TwelveBitEncoder
{
public static byte[] EncodeGray(ushort[] samples, int width, int height)
{
int bw = (width + 7) / 8, bh = (height + 7) / 8;
var blocks = new short[bw * bh][];
for (var by = 0; by < bh; by++)
{
for (var bx = 0; bx < bw; bx++)
{
var coef = new short[64];
for (var v = 0; v < 8; v++)
{
for (var u = 0; u < 8; u++)
{
double sum = 0;
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
var s = samples[Math.Min(by * 8 + y, height - 1) * width + Math.Min(bx * 8 + x, width - 1)] - 2048.0;
sum += s * JpegTables.Basis[u * 8 + x] * JpegTables.Basis[v * 8 + y];
}
}
coef[v * 8 + u] = (short)Math.Round(sum);
}
}
blocks[by * bw + bx] = coef;
}
}
var dcFreq = new long[256];
var acFreq = new long[256];
Walk(blocks, (dc, s) => (dc ? dcFreq : acFreq)[s]++, null);
var dcCode = JpegHuffmanCode.Optimal(dcFreq);
var acCode = JpegHuffmanCode.Optimal(acFreq);
var writer = new JpegBitWriter(1 << 16);
Walk(blocks, (dc, s) => { var c = dc ? dcCode : acCode; writer.Reserve(8); writer.Write(c.Code[s], c.Length[s]); }, (v, s) => writer.Write((uint)((v < 0 ? v - 1 : v) & ((1 << s) - 1)), s));
writer.Flush();
using var ms = new MemoryStream();
ms.Write([0xFF, 0xD8]);
var dqt = new byte[129];
dqt[0] = 0x10;
for (var k = 0; k < 64; k++) dqt[2 + 2 * k] = 1;
JpegEncoder.Segment(ms, 0xDB, dqt);
JpegEncoder.Segment(ms, 0xC1, [12, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 1, 1, 0x11, 0]);
var dht = new MemoryStream();
dht.WriteByte(0x00);
dht.Write(dcCode.Bits);
dht.Write(dcCode.Values);
dht.WriteByte(0x10);
dht.Write(acCode.Bits);
dht.Write(acCode.Values);
JpegEncoder.Segment(ms, 0xC4, dht.ToArray());
JpegEncoder.Segment(ms, 0xDA, [1, 1, 0x00, 0, 63, 0]);
ms.Write(writer.Written);
ms.Write([0xFF, 0xD9]);
return ms.ToArray();
}
private static void Walk(short[][] blocks, Action<bool, int> symbol, Action<int, int>? bits)
{
var pred = 0;
foreach (var b in blocks)
{
var diff = b[0] - pred;
pred = b[0];
var s = Size(diff);
symbol(true, s);
if (s > 0) bits?.Invoke(diff, s);
var run = 0;
for (var k = 1; k < 64; k++)
{
int v = b[JpegTables.NaturalOrder[k]];
if (v == 0)
{
run++;
continue;
}
for (; run >= 16; run -= 16) symbol(false, 0xF0);
s = Size(v);
symbol(false, run << 4 | s);
bits?.Invoke(v, s);
run = 0;
}
if (run > 0) symbol(false, 0);
}
}
private static int Size(int v) => v == 0 ? 0 : 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)Math.Abs(v));
}
}
@@ -0,0 +1,107 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Testing;
namespace Chronos.Core.Tests.Codecs;
/// <summary>Lossless JPEG (SOF3) round trips: every predictor, precisions 2–16, components, restarts.</summary>
public sealed class JpegLosslessTests
{
private static ushort[] Raw(int width, int height, int components, int precision, int seed)
{
var rng = new Random(seed);
var max = (1 << precision) - 1;
var samples = new ushort[width * height * components];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
for (var c = 0; c < components; c++)
{
// Smooth ramp + sensor noise, with a few clipped highlights and black pixels.
var v = (x * 3 + y * 5 + c * 97) % (max + 1) * 0.7 + rng.Next(Math.Max(1, max / 64));
if (rng.Next(200) == 0) v = max;
if (rng.Next(300) == 0) v = 0;
samples[(y * width + x) * components + c] = (ushort)Math.Clamp((int)v, 0, max);
}
}
}
return samples;
}
[Theory]
[Case(1)]
[Case(2)]
[Case(3)]
[Case(4)]
[Case(5)]
[Case(6)]
[Case(7)]
public void EveryPredictorRoundTrips(int predictor)
{
var samples = Raw(37, 23, 3, 12, predictor);
var jpeg = JpegLosslessEncoder.Encode(samples, 37, 23, 3, 12, predictor);
var decoded = JpegLosslessDecoder.Decode(jpeg);
Assert.Equal(37, decoded.Width);
Assert.Equal(23, decoded.Height);
Assert.Equal(3, decoded.Components);
Assert.Equal(12, decoded.Precision);
Assert.SequenceEqual(samples, decoded.Samples);
}
[Theory]
[Case(2, 1)]
[Case(8, 1)]
[Case(14, 2)]
[Case(16, 1)]
[Case(16, 4)]
public void PrecisionsAndComponentCounts(int precision, int components)
{
var samples = Raw(19, 11, components, precision, precision);
foreach (var predictor in new[] { 1, 4, 7 })
{
var decoded = JpegLosslessDecoder.Decode(JpegLosslessEncoder.Encode(samples, 19, 11, components, precision, predictor));
Assert.SequenceEqual(samples, decoded.Samples);
}
}
[Theory]
[Case(1)]
[Case(19)]
[Case(25)]
[Case(64)]
public void RestartIntervalsRoundTrip(int interval)
{
var samples = Raw(19, 13, 2, 14, interval);
foreach (var predictor in new[] { 1, 6 })
{
var jpeg = JpegLosslessEncoder.Encode(samples, 19, 13, 2, 14, predictor, restartInterval: interval);
Assert.SequenceEqual(samples, JpegLosslessDecoder.Decode(jpeg).Samples);
}
}
[Test]
public void PointTransformRestoresScaledSamples()
{
var samples = Raw(16, 9, 1, 16, 3).Select(s => (ushort)(s & ~7)).ToArray();
var jpeg = JpegLosslessEncoder.Encode(samples, 16, 9, 1, 16, predictor: 5, pointTransform: 3);
Assert.SequenceEqual(samples, JpegLosslessDecoder.Decode(jpeg).Samples);
}
[Test]
public void GeneralDecoderExposesLosslessAsImage()
{
var samples = Raw(10, 6, 3, 8, 1);
var image = JpegDecoder.Decode(JpegLosslessEncoder.Encode(samples, 10, 6, 3, 8));
Assert.Equal(JpegProcess.Lossless, image.Info.Process);
Assert.Equal(3, image.Components);
Assert.SequenceEqual(samples.Select(s => (byte)s), image.Pixels8!);
var wide = Raw(10, 6, 1, 14, 2);
var gray = JpegDecoder.Decode(JpegLosslessEncoder.Encode(wide, 10, 6, 1, 14));
Assert.Equal(14, gray.BitDepth);
Assert.SequenceEqual(wide, gray.Pixels16!);
}
[Test]
public void DctStreamIsRejectedByLosslessDecoder() =>
Assert.Throws<InvalidDataException>(() => JpegLosslessDecoder.Decode(JpegEncoder.Encode(new byte[48], 4, 4, 3)));
}
@@ -0,0 +1,70 @@
using System.Diagnostics;
using System.Reflection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Testing;
namespace Chronos.Core.Tests.Codecs;
/// <summary>24-megapixel baseline 4:2:0 encode/decode timing (decode measured single-threaded).</summary>
[Serial]
[Category("Performance")]
public sealed class JpegPerformanceTests(TestContext context)
{
private const int W = 6000, H = 4000;
[Test]
[Timeout(60_000)]
public void Decodes24MegapixelOnOneCoreUnderThreeSeconds()
{
// A Debug build disables the JIT optimiser in Chronos.Core: timings would measure the build, not the codec.
if (typeof(JpegDecoder).Assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITOptimizerDisabled == true)
TestContext.Skip("timing gate needs an optimised build (dotnet run -c Release)");
var rgb = Photo();
var sw = Stopwatch.StartNew();
var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 });
var encode = sw.Elapsed;
// Best of two runs: the machine is shared, the first run also pays JIT warm-up.
var single = TimeSpan.MaxValue;
JpegImage? image = null;
for (var run = 0; run < 2; run++)
{
sw.Restart();
image = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxDegreeOfParallelism = 1 });
single = sw.Elapsed < single ? sw.Elapsed : single;
}
sw.Restart();
JpegDecoder.Decode(jpeg);
var parallel = sw.Elapsed;
context.Log($"encode {encode.TotalMilliseconds:F0} ms ({W * (double)H / 1e6 / encode.TotalSeconds:F1} MP/s, {jpeg.Length / 1e6:F2} MB); " +
$"decode 1 core {single.TotalMilliseconds:F0} ms ({W * (double)H / 1e6 / single.TotalSeconds:F1} MP/s); " +
$"decode all cores {parallel.TotalMilliseconds:F0} ms");
Console.WriteLine($"[perf] {context.LogText.Trim()}");
Assert.Equal(W, image!.Width);
Assert.Less(single.TotalSeconds, 3.0);
}
/// <summary>Photo-like content: smooth illumination, texture and mild noise (≈ q90 file size of a real photo).</summary>
private static byte[] Photo()
{
var rgb = new byte[W * H * 3];
Parallel.For(0, H, y =>
{
var state = (uint)(y * 2654435761u + 1);
for (var x = 0; x < W; x++)
{
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
var noise = (int)(state & 7) - 4;
var texture = ((x >> 3) ^ (y >> 3)) & 15;
var i = (y * W + x) * 3;
rgb[i] = (byte)Math.Clamp(60 + x * 150 / W + texture + noise, 0, 255);
rgb[i + 1] = (byte)Math.Clamp(80 + y * 120 / H + texture + noise, 0, 255);
rgb[i + 2] = (byte)Math.Clamp(200 - (x + y) * 140 / (W + H) + noise, 0, 255);
}
});
return rgb;
}
}
@@ -0,0 +1,157 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Testing;
using static Chronos.Core.Tests.Codecs.CodecTestData;
namespace Chronos.Core.Tests.Codecs;
/// <summary>Corrupt, truncated and hostile JPEG input: only <see cref="InvalidDataException"/> may escape.</summary>
public sealed class JpegRobustnessTests(TestContext context)
{
private static byte[] LosslessSample()
{
var samples = new ushort[24 * 10 * 2];
for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i * 37 % 4096);
return JpegLosslessEncoder.Encode(samples, 24, 10, 2, 12, predictor: 6, restartInterval: 24);
}
[Theory]
[Case("jpeg/b420.jpg")]
[Case("jpeg/b411.jpg")]
[Case("jpeg/p420.jpg")]
[Case("jpeg/p444.jpg")]
[Case("jpeg/r420.jpg")]
[Case("jpeg/pgray.jpg")]
[Case("jpeg/cmyk.jpg")]
[Case("lossless")]
public void FuzzedInputOnlyThrowsInvalidData(string source)
{
var valid = source == "lossless" ? LosslessSample() : Fixture(source);
var options = new[] { JpegDecodeOptions.Default, new JpegDecodeOptions { MaxLongEdge = 16, FancyUpsampling = false } };
int decoded = 0, rejected = 0;
var i = 0;
foreach (var input in Corruptions(valid, 120, seed: source.Sum(c => c)))
{
try
{
JpegDecoder.ReadInfo(input);
if (source == "lossless")
{
var raw = JpegLosslessDecoder.Decode(input);
Assert.Equal(raw.Width * raw.Height * raw.Components, raw.Samples.Length);
}
else
{
var image = JpegDecoder.Decode(input, options[i++ % 2]);
Assert.True(image.Width > 0 && image.Height > 0);
}
decoded++;
}
catch (InvalidDataException)
{
rejected++;
}
}
context.Log($"{source}: {decoded} decoded (possibly partial), {rejected} rejected");
}
[Test]
public void CorruptRestartIntervalIsResynchronised()
{
var data = Fixture("jpeg/r420.jpg");
var reference = ReadPnm(Fixture("jpeg/r420.ppm")).Samples;
var rst0 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD0]);
var rst1 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD1]);
Assert.True(rst0 > 0 && rst1 > rst0, "fixture has restart markers");
var corrupt = (byte[])data.Clone();
var rng = new Random(5);
for (var p = rst0 + 6; p < rst1 - 4; p += 3)
{
if (corrupt[p - 1] != 0xFF) corrupt[p] = (byte)rng.Next(0xFF);
}
// A bogus marker inside the damaged interval must be skipped, as libjpeg's resync does.
corrupt[rst0 + 10] = 0xFF;
corrupt[rst0 + 11] = 0x3A;
var image = JpegDecoder.Decode(corrupt);
context.Log(string.Join("; ", image.Warnings));
Assert.NotEmpty(image.Warnings);
AssertRowsMatch(image.Pixels8!, reference, 0, 14);
AssertRowsMatch(image.Pixels8!, reference, 34, 45);
}
[Test]
public void MissingRestartMarkerSkipsTheLostInterval()
{
var data = Fixture("jpeg/r420.jpg");
var reference = ReadPnm(Fixture("jpeg/r420.ppm")).Samples;
var rst0 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD0]);
var cut = data.AsSpan(0, rst0).ToArray().Concat(data.AsSpan(rst0 + 2).ToArray()).ToArray();
var image = JpegDecoder.Decode(cut);
Assert.NotEmpty(image.Warnings);
AssertRowsMatch(image.Pixels8!, reference, 0, 14);
AssertRowsMatch(image.Pixels8!, reference, 34, 45);
}
[Theory]
[Case("jpeg/p420.jpg")]
[Case("jpeg/b444.jpg")]
public void TruncatedScanDataYieldsPartialImage(string name)
{
var data = Fixture(name);
var image = JpegDecoder.Decode(data.AsSpan(0, data.Length * 2 / 3));
Assert.Equal(61, image.Width);
Assert.Equal(45, image.Height);
Assert.NotEmpty(image.Warnings);
}
[Test]
public void StructuralErrorsAreRejected()
{
Assert.Throws<InvalidDataException>(() => JpegDecoder.Decode([]));
Assert.Throws<InvalidDataException>(() => JpegDecoder.Decode([0xFF, 0xD8, 0xFF, 0xD9]));
Assert.Throws<InvalidDataException>(() => JpegDecoder.ReadInfo([0x89, 0x50, 0x4E, 0x47]));
var arithmetic = Fixture("jpeg/b420.jpg");
var sof = arithmetic.AsSpan().IndexOf([(byte)0xFF, (byte)0xC0]);
arithmetic[sof + 1] = 0xC9;
Assert.Throws<InvalidDataException>(() => JpegDecoder.Decode(arithmetic));
var huge = Fixture("jpeg/b420.jpg");
huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF;
Assert.Throws<InvalidDataException>(() => JpegDecoder.Decode(huge));
}
[Test]
public void TablesStreamFeedsAbbreviatedImage()
{
// TIFF JPEGTables layout: tables in one SOI..EOI stream, the image without DQT/DHT.
var full = Fixture("jpeg/b420.jpg");
var tables = new MemoryStream();
var image = new MemoryStream();
tables.Write([0xFF, 0xD8]);
image.Write([0xFF, 0xD8]);
var pos = 2;
while (pos < full.Length)
{
var marker = full[pos + 1];
if (marker == 0xDA)
{
image.Write(full.AsSpan(pos));
break;
}
var length = full[pos + 2] << 8 | full[pos + 3];
(marker is 0xDB or 0xC4 ? tables : image).Write(full.AsSpan(pos, length + 2));
pos += length + 2;
}
tables.Write([0xFF, 0xD9]);
Assert.Throws<InvalidDataException>(() => JpegDecoder.Decode(image.ToArray()));
var decoded = JpegDecoder.Decode(image.ToArray(), new JpegDecodeOptions { Tables = tables.ToArray() });
Assert.BytesEqual(JpegDecoder.Decode(full).Pixels8, decoded.Pixels8);
}
private static void AssertRowsMatch(byte[] actual, int[] reference, int fromRow, int toRow)
{
var rowBytes = 61 * 3;
for (var i = fromRow * rowBytes; i < toRow * rowBytes; i++)
{
if (Math.Abs(actual[i] - reference[i]) > 2) Assert.Fail($"row {i / rowBytes} differs from the reference");
}
}
}
@@ -0,0 +1,94 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Testing;
using static Chronos.Core.Tests.Codecs.CodecTestData;
namespace Chronos.Core.Tests.Codecs;
/// <summary>DCT-domain scaling (1/2, 1/4, 1/8) and the linear-light decode path.</summary>
public sealed class JpegScalingTests(TestContext context)
{
private const int W = 256, H = 192;
[Theory]
[Case(0, 256, 192)]
[Case(200, 256, 192)]
[Case(128, 128, 96)]
[Case(100, 128, 96)]
[Case(64, 64, 48)]
[Case(33, 64, 48)]
[Case(32, 32, 24)]
[Case(1, 32, 24)]
public void MaxLongEdgePicksSmallestSufficientScale(int maxLongEdge, int width, int height)
{
var jpeg = JpegEncoder.Encode(SmoothImage(W, H), W, H, 3);
var image = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxLongEdge = maxLongEdge });
Assert.Equal(width, image.Width);
Assert.Equal(height, image.Height);
Assert.Equal(W, image.Info.Width);
}
[Theory]
[Case(2, 38.0)]
[Case(4, 34.0)]
[Case(8, 30.0)]
public void ScaledDecodeApproximatesAreaAverage(int factor, double minPsnr)
{
var jpeg = JpegEncoder.Encode(SmoothImage(W, H), W, H, 3, new JpegEncodeOptions { Quality = 92 });
var full = JpegDecoder.Decode(jpeg).Pixels8!;
var scaled = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxLongEdge = W / factor });
Assert.Equal(W / factor, scaled.Width);
int sw = W / factor, sh = H / factor;
var expected = new byte[sw * sh * 3];
for (var y = 0; y < sh; y++)
{
for (var x = 0; x < sw; x++)
{
for (var c = 0; c < 3; c++)
{
var sum = 0;
for (var dy = 0; dy < factor; dy++)
{
for (var dx = 0; dx < factor; dx++) sum += full[((y * factor + dy) * W + x * factor + dx) * 3 + c];
}
expected[(y * sw + x) * 3 + c] = (byte)((sum + factor * factor / 2) / (factor * factor));
}
}
}
var psnr = Psnr(scaled.Pixels8, expected);
context.Log($"1/{factor}: {psnr:F1} dB vs area average");
Assert.Greater(psnr, minPsnr);
}
[Test]
public void ScaledOddSizeKeepsEdges()
{
var image = JpegDecoder.Decode(Fixture("jpeg/b420.jpg"), new JpegDecodeOptions { MaxLongEdge = 31 });
Assert.Equal(31, image.Width);
Assert.Equal(23, image.Height);
var reference = ReadPnm(Fixture("src.ppm"));
// Bottom-right pixel of the scaled image must still resemble the source corner (no padding garbage).
var pixels = image.Pixels8!;
var last = pixels.AsSpan(pixels.Length - 3);
var src = reference.Samples.AsSpan(reference.Samples.Length - 3);
for (var c = 0; c < 3; c++) Assert.InRange(last[c], src[c] - 70, src[c] + 70);
}
[Test]
public void LinearDecodeMatchesLookupOfEightBitDecode()
{
var data = Fixture("jpeg/b422.jpg");
var bytes = JpegDecoder.Decode(data).Pixels8!;
using var linear = JpegDecoder.DecodeToLinear(data);
Assert.Equal(3, linear.Channels);
for (var i = 0; i < 61 * 45; i += 17)
{
for (var c = 0; c < 3; c++) Assert.Equal(ColorSpace.Linear8(bytes[i * 3 + c]), linear.Plane(c)[i]);
}
using var gray = JpegDecoder.DecodeToLinear(Fixture("jpeg/gray.jpg"));
Assert.Equal(1, gray.Channels);
using var expanded = JpegDecoder.DecodeToLinear(Fixture("jpeg/gray.jpg"), expandGray: true);
Assert.Equal(3, expanded.Channels);
Assert.SequenceEqual(gray.Plane(0).ToArray(), expanded.Plane(2).ToArray());
}
}
@@ -0,0 +1,124 @@
using Chronos.Core.Codecs.Dng;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
using Chronos.Testing;
namespace Chronos.Core.Tests.Codecs;
public sealed class LinearDngWriterTests
{
private static ImageBuffer Scene(int w, int h)
{
var image = new ImageBuffer(w, h);
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
image[0, x, y] = x / (float)(w - 1);
image[1, x, y] = y / (float)(h - 1) * 0.6f;
image[2, x, y] = (x * y % 97) / 96f;
}
}
image[0, 0, 0] = 1.7f; // highlight above white: clipped
return image;
}
[Theory]
[Case(DngCompression.LosslessJpeg)]
[Case(DngCompression.Uncompressed)]
public void PixelsRoundTripThroughTheTiffReader(DngCompression compression)
{
using var image = Scene(300, 70);
var dng = LinearDngWriter.Write(image, new LinearDngOptions { Compression = compression, TileSize = 128 });
var reader = TiffReader.Open(new MemoryStream(dng))!;
var raster = TiffImageReader.ReadRaster(reader, reader.ReadChain()[0]);
Assert.Empty(raster.Warnings);
Assert.Equal(34892, raster.Photometric);
Assert.SequenceEqual(PixelConvert.ToInterleaved16(image, 3, TransferFunction.Linear), raster.Samples!);
using var back = TiffImageReader.Decode(dng);
Assert.Approximately(1.0, back[0, 0, 0], 1e-6);
for (var i = 1; i < image.Data.Length; i += 37)
{
Assert.Approximately(Math.Clamp(image.Data[i], 0, 1), back.Data[i], 1.0 / 65535);
}
}
[Test]
public void TagsDescribeLinearRec709()
{
using var image = Scene(40, 30);
var dng = LinearDngWriter.Write(image);
var r = TiffReader.Open(new MemoryStream(dng))!;
Assert.True(r.LittleEndian);
var ifd = r.ReadChain()[0];
Assert.SequenceEqual(new uint[] { 1, 4, 0, 0 }, r.GetUInts(ifd, TiffTags.DngVersion)!);
Assert.Equal(0u, r.GetUInt(ifd, TiffTags.NewSubfileType));
Assert.Equal(34892u, r.GetUInt(ifd, TiffTags.PhotometricInterpretation));
Assert.Equal(3u, r.GetUInt(ifd, TiffTags.SamplesPerPixel));
Assert.SequenceEqual(new uint[] { 16, 16, 16 }, r.GetUInts(ifd, TiffTags.BitsPerSample)!);
Assert.Equal(7u, r.GetUInt(ifd, TiffTags.Compression));
Assert.Equal("Chronos", r.GetString(ifd, TiffTags.UniqueCameraModel));
Assert.Equal(21u, r.GetUInt(ifd, TiffTags.CalibrationIlluminant1));
Assert.SequenceEqual(new[] { 1.0, 1.0, 1.0 }, r.GetDoubles(ifd, TiffTags.AsShotNeutral)!);
Assert.Equal(0.0, r.GetDouble(ifd, TiffTags.BaselineExposure));
Assert.SequenceEqual(new uint[] { 65535, 65535, 65535 }, r.GetUInts(ifd, TiffTags.WhiteLevel)!);
Assert.True(ifd.Has(TiffTags.TileWidth) && ifd.Has(TiffTags.TileOffsets) && ifd.Has(TiffTags.TileByteCounts));
// ColorMatrix1 maps XYZ to camera space: D65 white must land on the camera neutral (1, 1, 1),
// and its product with sRGB → XYZ(D65) must be the identity (camera space = linear sRGB).
var cm = r.GetDoubles(ifd, TiffTags.ColorMatrix1)!;
Assert.Equal(9, cm.Length);
double[] d65 = [0.95047, 1.0, 1.08883];
double[] srgbToXyz = [0.4124564, 0.3575761, 0.1804375, 0.2126729, 0.7151522, 0.0721750, 0.0193339, 0.1191920, 0.9503041];
for (var row = 0; row < 3; row++)
{
Assert.Approximately(1.0, cm[row * 3] * d65[0] + cm[row * 3 + 1] * d65[1] + cm[row * 3 + 2] * d65[2], 2e-3);
for (var col = 0; col < 3; col++)
{
var p = 0.0;
for (var k = 0; k < 3; k++) p += cm[row * 3 + k] * srgbToXyz[k * 3 + col];
Assert.Approximately(row == col ? 1 : 0, p, 2e-4);
}
}
// ForwardMatrix1 maps the white-balanced neutral to D50 (the DNG SDK's xy 0.3457, 0.3585).
var fm = r.GetDoubles(ifd, TiffTags.ForwardMatrix1)!;
double[] d50 = [0.3457 / 0.3585, 1.0, (1 - 0.3457 - 0.3585) / 0.3585];
for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4);
}
[Test]
public void GrayInputExifAndNonSeekableOutput()
{
using var gray = new ImageBuffer(33, 20, 1);
for (var i = 0; i < gray.PlaneLength; i++) gray.Plane(0)[i] = i / (float)gray.PlaneLength;
using var sink = new MemoryStream();
LinearDngWriter.Write(new ForwardOnlyStream(sink), gray, new LinearDngOptions { Exif = TiffTests.ExifBlock() });
var dng = sink.ToArray();
TiffTests.AssertExif(dng);
using var back = TiffImageReader.Decode(dng);
Assert.Equal(3, back.Channels);
Assert.Approximately(gray[0, 20, 10], back[2, 20, 10], 1.0 / 65535);
}
/// <summary>A write-only, non-seekable stream (pipes, network) to exercise the buffering path.</summary>
private sealed class ForwardOnlyStream(Stream inner) : Stream
{
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
public override void Flush() => inner.Flush();
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
}
}
+278
View File
@@ -0,0 +1,278 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Chronos.Core.Codecs.Png;
using Chronos.Core.Imaging;
using Chronos.Testing;
using static Chronos.Core.Tests.Codecs.CodecTestData;
namespace Chronos.Core.Tests.Codecs;
public sealed class PngTests(TestContext context)
{
[Theory]
[Case("png/adam7.png", false)]
[Case("png/rgb16.png", true)]
[Case("png/adam7-16.png", true)]
public void RgbFixturesMatchSource(string name, bool sixteen)
{
var image = PngDecoder.Decode(Fixture(name));
Assert.Equal(3, image.Channels);
Assert.Empty(image.Warnings);
if (sixteen) Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, image.Pixels16!);
else Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Bytes, image.Pixels8!);
}
[Theory]
[Case("gray1", 1)]
[Case("gray2", 1)]
[Case("gray4", 1)]
[Case("gray8", 1)]
[Case("graya", 2)]
[Case("palette4", 3)]
[Case("palette-adam7", 3)]
[Case("palette-trns", 4)]
[Case("rgba", 4)]
public void LibpngFixturesMatchReference(string name, int channels)
{
var image = PngDecoder.Decode(Fixture($"png/{name}.png"));
var reference = ReadPnm(Fixture($"png/{name}.pam"));
Assert.Equal(channels, image.Channels);
Assert.Empty(image.Warnings);
var pixels = image.Pixels8!;
for (var i = 0; i < image.Width * image.Height; i++)
{
for (var c = 0; c < channels; c++)
{
// ImageMagick expands gray to RGB in PAM; compare against its first channel.
var refChannel = reference.Channels == channels ? c : c == channels - 1 && channels == 2 ? reference.Channels - 1 : 0;
if (pixels[i * channels + c] != reference.Samples[i * reference.Channels + refChannel])
Assert.Fail($"{name}: pixel {i} channel {c}: {pixels[i * channels + c]} vs {reference.Samples[i * reference.Channels + refChannel]}");
}
}
}
[Theory]
[Case(PngColorType.Gray, 8)]
[Case(PngColorType.Gray, 16)]
[Case(PngColorType.GrayAlpha, 8)]
[Case(PngColorType.GrayAlpha, 16)]
[Case(PngColorType.Rgb, 8)]
[Case(PngColorType.Rgb, 16)]
[Case(PngColorType.Rgba, 8)]
[Case(PngColorType.Rgba, 16)]
public void EncoderRoundTrips(PngColorType type, int depth)
{
const int w = 37, h = 21;
var channels = type switch { PngColorType.Gray => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 };
var bytes = new byte[w * h * channels * depth / 8];
new Random(depth * 10 + channels).NextBytes(bytes.AsSpan(bytes.Length / 2));
for (var i = 0; i < bytes.Length / 2; i++) bytes[i] = (byte)(i * 7);
var image = PngDecoder.Decode(PngEncoder.Encode(bytes, w, h, type, depth));
Assert.Equal(channels, image.Channels);
if (depth == 8)
{
Assert.SequenceEqual(bytes, image.Pixels8!);
}
else
{
var words = new ushort[bytes.Length / 2];
for (var i = 0; i < words.Length; i++) words[i] = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(2 * i));
Assert.SequenceEqual(words, image.Pixels16!);
}
}
[Theory]
[Case(0)]
[Case(1)]
[Case(2)]
[Case(3)]
[Case(4)]
public void EveryFilterTypeDecodes(int filter)
{
const int w = 23, h = 9;
var rgb = TestCard(w, h);
var png = RawPng(w, h, PngColorType.Rgb, 8, rgb, filter);
Assert.SequenceEqual(rgb, PngDecoder.Decode(png).Pixels8!);
var rgba16 = new byte[w * h * 8];
new Random(filter).NextBytes(rgba16);
var wide = PngDecoder.Decode(RawPng(w, h, PngColorType.Rgba, 16, rgba16, filter, interlaced: true));
Assert.Equal((ushort)(rgba16[8 * 5] << 8 | rgba16[8 * 5 + 1]), wide.Pixels16![4 * 5]);
}
[Theory]
[Case(1)]
[Case(2)]
[Case(4)]
public void SubBytePaletteWithTransparency(int depth)
{
const int w = 13, h = 7;
var colours = 1 << depth;
var indices = new byte[w * h];
for (var i = 0; i < indices.Length; i++) indices[i] = (byte)(i * 5 % colours);
var packed = Pack(indices, w, h, depth);
var plte = new byte[colours * 3];
for (var i = 0; i < plte.Length; i++) plte[i] = (byte)(i * 37);
var trns = new byte[] { 0, 128 };
var png = RawPng(w, h, PngColorType.Palette, depth, packed, 4, interlaced: depth == 2, ("PLTE", plte), ("tRNS", trns));
var image = PngDecoder.Decode(png);
Assert.Equal(4, image.Channels);
for (var i = 0; i < indices.Length; i++)
{
int idx = indices[i];
Assert.Equal(plte[3 * idx + 1], image.Pixels8![4 * i + 1]);
Assert.Equal(idx < trns.Length ? trns[idx] : (byte)255, image.Pixels8[4 * i + 3]);
}
}
[Test]
public void ColourKeyTransparency()
{
var gray = PngDecoder.Decode(RawPng(4, 1, PngColorType.Gray, 4, [0x0F, 0x3F], 0, false, ("tRNS", [0, 3])));
Assert.SequenceEqual(new byte[] { 0, 255, 255, 255, 51, 0, 255, 255 }, gray.Pixels8!);
var rgb16 = new byte[12];
rgb16[1] = 9;
var keyed = PngDecoder.Decode(RawPng(2, 1, PngColorType.Rgb, 16, rgb16, 1, false, ("tRNS", [0, 0, 0, 0, 0, 0])));
Assert.Equal(4, keyed.Channels);
Assert.Equal(ushort.MaxValue, keyed.Pixels16![3]);
Assert.Equal((ushort)0, keyed.Pixels16[7]);
}
[Test]
public void CrcMismatchIsToleratedWithWarning()
{
var png = PngEncoder.Encode(TestCard(8, 8), 8, 8, PngColorType.Rgb);
png[^13] ^= 0xFF; // last byte of the IDAT CRC (IEND is the final 12 bytes)
var image = PngDecoder.Decode(png);
Assert.SequenceEqual(TestCard(8, 8), image.Pixels8!);
Assert.Contains("CRC", string.Join(";", image.Warnings));
}
[Test]
public void ImageBufferRoundTripsAtSixteenBits()
{
using var image = new ImageBuffer(33, 17, 4);
for (var c = 0; c < 4; c++)
{
var plane = image.Plane(c);
for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 1) % 97) / 96f;
}
var png = PngEncoder.Encode(image, 16);
Assert.True(png.AsSpan().IndexOf("sRGB"u8) > 0, "sRGB chunk");
using var back = PngDecoder.DecodeToLinear(png, keepAlpha: true);
Assert.Equal(4, back.Channels);
for (var i = 0; i < image.Data.Length; i += 13) Assert.Approximately(image.Data[i], back.Data[i], 2e-4);
using var eight = PngDecoder.DecodeToLinear(PngEncoder.Encode(image));
Assert.Equal(3, eight.Channels);
Assert.Approximately(image[1, 5, 5], eight[1, 5, 5], 0.01);
}
[Theory]
[Case("png/adam7.png")]
[Case("png/palette-trns.png")]
[Case("png/gray2.png")]
[Case("png/adam7-16.png")]
public void FuzzedInputOnlyThrowsInvalidData(string name)
{
int ok = 0, rejected = 0;
foreach (var input in Corruptions(Fixture(name), 150, seed: name.Length))
{
try
{
var image = PngDecoder.Decode(input);
Assert.True(image.Width > 0);
ok++;
}
catch (InvalidDataException)
{
rejected++;
}
}
context.Log($"{name}: {ok} decoded, {rejected} rejected");
}
[Test]
public void StructuralErrorsAreRejected()
{
Assert.Throws<InvalidDataException>(() => PngDecoder.Decode([]));
Assert.Throws<InvalidDataException>(() => PngDecoder.Decode(Fixture("jpeg/b420.jpg")));
var palette = Fixture("png/palette4.png");
var plte = palette.AsSpan().IndexOf("PLTE"u8);
palette[plte] = (byte)'X'; // drop the palette (and make an unknown critical chunk)
Assert.Throws<InvalidDataException>(() => PngDecoder.Decode(palette));
Assert.Throws<ArgumentException>(() => PngEncoder.Encode(new byte[4], 2, 2, PngColorType.Palette));
}
/// <summary>Builds a PNG with every row filtered by <paramref name="filter"/> (test-side writer).</summary>
private static byte[] RawPng(int w, int h, PngColorType type, int depth, byte[] rows, int filter, bool interlaced = false, params (string Type, byte[] Data)[] chunks)
{
var channels = type switch { PngColorType.Gray or PngColorType.Palette => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 };
var bits = channels * depth;
var bpp = Math.Max(1, bits / 8);
var stride = (w * bits + 7) / 8;
var passes = interlaced
? new[] { (0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2) }
: [(0, 0, 1, 1)];
using var raw = new MemoryStream();
foreach (var (px, py, dx, dy) in passes)
{
if (px >= w || py >= h) continue;
var count = (w - px + dx - 1) / dx;
var rowBytes = (count * bits + 7) / 8;
var prev = new byte[rowBytes];
for (var y = py; y < h; y += dy)
{
// Gather this pass's pixels (bit-exact copy of their samples).
var row = new byte[rowBytes];
for (int i = 0, x = px; i < count; i++, x += dx)
{
for (var b = 0; b < bits; b++)
{
var src = y * stride * 8 + x * bits + b;
if ((rows[src >> 3] >> (7 - (src & 7)) & 1) != 0) row[(i * bits + b) >> 3] |= (byte)(0x80 >> ((i * bits + b) & 7));
}
}
raw.WriteByte((byte)filter);
for (var i = 0; i < rowBytes; i++)
{
int a = i >= bpp ? row[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0;
var predicted = filter switch { 0 => 0, 1 => a, 2 => b, 3 => (a + b) >> 1, _ => PngEncoder.Paeth(a, b, c) };
raw.WriteByte((byte)(row[i] - predicted));
}
prev = row;
}
}
using var z = new MemoryStream();
using (var deflate = new ZLibStream(z, CompressionLevel.Fastest, leaveOpen: true)) deflate.Write(raw.ToArray());
using var png = new MemoryStream();
png.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
var ihdr = new byte[13];
BinaryPrimitives.WriteInt32BigEndian(ihdr, w);
BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), h);
ihdr[8] = (byte)depth;
ihdr[9] = (byte)type;
ihdr[12] = (byte)(interlaced ? 1 : 0);
PngEncoder.WriteChunk(png, "IHDR", ihdr);
foreach (var (t, d) in chunks) PngEncoder.WriteChunk(png, t, d);
var compressed = z.ToArray();
var half = compressed.Length / 2;
PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(0, half));
PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(half));
PngEncoder.WriteChunk(png, "IEND", []);
return png.ToArray();
}
private static byte[] Pack(byte[] values, int w, int h, int depth)
{
var stride = (w * depth + 7) / 8;
var packed = new byte[stride * h];
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
var bit = x * depth;
packed[y * stride + (bit >> 3)] |= (byte)(values[y * w + x] << (8 - depth - (bit & 7)));
}
}
return packed;
}
}
@@ -0,0 +1,127 @@
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Metadata.Tiff;
namespace Chronos.Core.Tests.Codecs;
/// <summary>Test-side encoders for TIFF compressions the product never writes (LZW, PackBits) and a raw TIFF builder.</summary>
internal static class TiffTestEncoders
{
/// <summary>TIFF LZW; <paramref name="oldStyle"/> writes LSB-first codes switching width one code late (pre-6.0 libtiff).</summary>
public static byte[] Lzw(ReadOnlySpan<byte> data, bool oldStyle = false)
{
var output = new List<byte>();
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];
}
/// <summary>PackBits with both literal and replicate runs.</summary>
public static byte[] PackBits(ReadOnlySpan<byte> data)
{
var output = new List<byte>();
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];
}
/// <summary>Builds a little-endian TIFF from pre-encoded strips or tiles plus layout tags.</summary>
public static byte[] Build(Action<TiffDirectory> tags, IReadOnlyList<byte[]> 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();
}
}
@@ -0,0 +1,329 @@
using System.Buffers.Binary;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Codecs.Tiff;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata.Tiff;
using Chronos.Testing;
using static Chronos.Core.Tests.Codecs.CodecTestData;
namespace Chronos.Core.Tests.Codecs;
public sealed class TiffTests(TestContext context)
{
private static TiffRaster Raster(byte[] tiff, TiffDecodeOptions? options = null)
{
var reader = TiffReader.Open(new MemoryStream(tiff)) ?? throw new InvalidDataException("not a TIFF");
return TiffImageReader.ReadRaster(reader, reader.ReadChain()[0], options);
}
[Theory]
[Case("tiff/lzw-pred.tif")]
[Case("tiff/packbits.tif")]
[Case("tiff/none-strips.tif")]
[Case("tiff/lzw-tiled.tif")]
[Case("tiff/planar-zip.tif")]
public void EightBitLayoutsMatchSource(string name)
{
var raster = Raster(Fixture(name));
Assert.Empty(raster.Warnings);
Assert.Equal(3, raster.SamplesPerPixel);
Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Words, raster.Samples!);
}
[Test]
public void SixteenBitDeflatePredictorMatchesSource()
{
var raster = Raster(Fixture("tiff/deflate16-pred.tif"));
Assert.Equal(16, raster.BitsPerSample);
Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, raster.Samples!);
}
[Test]
public void FloatingPointPredictorMatchesSource()
{
var raster = Raster(Fixture("tiff/float32-pred3.tif"));
Assert.Equal(TiffSampleFormat.Float, raster.SampleFormat);
var source = ReadPnm(Fixture("src16.ppm")).Samples;
for (var i = 0; i < source.Length; i++) Assert.Approximately(source[i] / 65535.0, raster.FloatSamples![i], 1e-6);
using var image = TiffImageReader.Decode(Fixture("tiff/float32-pred3.tif"));
Assert.Approximately(source[3 * 100 + 1] / 65535.0, image[1, 100 % 61, 100 / 61], 1e-6);
}
[Theory]
[Case("tiff/jpeg-ycbcr")]
[Case("tiff/jpeg-rgb")]
public void JpegCompressedStripsMatchLibtiff(string name)
{
var raster = Raster(Fixture(name + ".tif"));
Assert.Equal(2, raster.Photometric);
Assert.Empty(raster.Warnings);
var diff = MaxAbsDiff(raster.Samples!.Select(s => (byte)s).ToArray(), ReadPnm(Fixture(name + ".ppm")).Samples);
context.Log($"{name}: max |diff| vs libtiff {diff}");
Assert.LessOrEqual(diff, 2);
}
[Test]
public void MinIsWhiteIsInverted()
{
// The raster keeps stored values; the image inverts them (0 = white), as libtiff readers do.
var file = Fixture("tiff/gray-miniswhite.tif");
var raster = Raster(file);
Assert.Equal(0, raster.Photometric);
using var image = TiffImageReader.Decode(file);
Assert.Equal(1, image.Channels);
for (var i = 0; i < image.PlaneLength; i++) Assert.Equal(ColorSpace.Linear8((byte)(255 - raster.Samples![i])), image.Plane(0)[i]);
}
[Theory]
[Case(false)]
[Case(true)]
public void LzwBothBitOrdersAndTableResets(bool oldStyle)
{
const int w = 70, h = 64;
var pixels = new byte[w * h * 3];
new Random(3).NextBytes(pixels.AsSpan(0, pixels.Length / 2));
for (var i = pixels.Length / 2; i < pixels.Length; i++) pixels[i] = (byte)(i / 50);
var strips = new List<byte[]>();
for (var y = 0; y < h; y += 32) strips.Add(TiffTestEncoders.Lzw(pixels.AsSpan(y * w * 3, Math.Min(32, h - y) * w * 3), oldStyle));
var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 3, 8, compression: 5, rowsPerStrip: 32), strips, tiled: false);
var raster = Raster(tiff);
Assert.Empty(raster.Warnings);
Assert.SequenceEqual(pixels.Select(b => (ushort)b), raster.Samples!);
}
[Test]
public void PackBitsSixteenBitPlanarTiles()
{
const int w = 40, h = 24, tile = 16;
var samples = new ushort[w * h * 3];
for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i % 7 == 0 ? 60000 : i * 13);
var chunks = new List<byte[]>();
for (var plane = 0; plane < 3; plane++)
{
for (var ty = 0; ty < h; ty += tile)
{
for (var tx = 0; tx < w; tx += tile)
{
var raw = new byte[tile * tile * 2];
for (var y = 0; y < tile; y++)
{
for (var x = 0; x < tile; x++)
{
var v = ty + y < h && tx + x < w ? samples[((ty + y) * w + tx + x) * 3 + plane] : (ushort)0;
BinaryPrimitives.WriteUInt16LittleEndian(raw.AsSpan((y * tile + x) * 2), v);
}
}
chunks.Add(TiffTestEncoders.PackBits(raw));
}
}
}
var tiff = TiffTestEncoders.Build(d =>
{
Layout(d, w, h, 3, 16, compression: 32773);
d.Short(TiffTags.PlanarConfiguration, 2);
d.Long(TiffTags.TileWidth, tile);
d.Long(TiffTags.TileLength, tile);
}, chunks, tiled: true);
Assert.SequenceEqual(samples, Raster(tiff).Samples!);
}
[Test]
public void SingleStripLargerThanTheReaderCapDecodes()
{
// Photoshop-style single uncompressed strip of 70 MB (TiffReader reads at most 64 MB per call).
const int w = 5000, h = 7000;
var strip = new byte[w * h * 2];
for (var i = 0; i < strip.Length; i += 2) BinaryPrimitives.WriteUInt16LittleEndian(strip.AsSpan(i), (ushort)(i * 7));
var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 16, compression: 1), [strip], tiled: false);
var raster = Raster(tiff);
Assert.Empty(raster.Warnings);
Assert.Equal(unchecked((ushort)((w * h - 1) * 2 * 7)), raster.Samples![^1]);
Assert.Equal(unchecked((ushort)(12345 * 2 * 7)), raster.Samples[12345]);
}
[Test]
public void PackedTwelveBitSamplesUnpack()
{
const int w = 5, h = 3;
var values = Enumerable.Range(0, w * h).Select(i => (ushort)(i * 273 % 4096)).ToArray();
var stride = (w * 12 + 7) / 8;
var raw = new byte[stride * h];
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
for (var b = 0; b < 12; b++)
{
if ((values[y * w + x] >> (11 - b) & 1) != 0) raw[y * stride + (x * 12 + b) / 8] |= (byte)(0x80 >> ((x * 12 + b) % 8));
}
}
}
var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 12, compression: 1), [raw], tiled: false);
var raster = Raster(tiff);
Assert.Equal(12, raster.BitsPerSample);
Assert.SequenceEqual(values, raster.Samples!);
}
[Test]
public void DngStyleLosslessTilesMapBackFromReshapedFrames()
{
// A CFA-like 1-sample tile of 32×8 stored as a 2-component, 16-wide lossless JPEG frame (as DNG writers do).
const int w = 48, h = 8, tile = 32;
var samples = Enumerable.Range(0, w * h).Select(i => (ushort)(i * 977 % 16384)).ToArray();
var chunks = new List<byte[]>();
for (var tx = 0; tx < w; tx += tile)
{
var t = new ushort[tile * h];
for (var y = 0; y < h; y++)
{
for (var x = 0; x < tile; x++) t[y * tile + x] = tx + x < w ? samples[y * w + tx + x] : (ushort)0;
}
chunks.Add(JpegLosslessEncoder.Encode(t, tile / 2, h, 2, 14, predictor: 1));
}
var tiff = TiffTestEncoders.Build(d =>
{
Layout(d, w, h, 1, 16, compression: 7);
d.Short(TiffTags.PhotometricInterpretation, 32803);
d.Long(TiffTags.TileWidth, tile);
d.Long(TiffTags.TileLength, h);
}, chunks, tiled: true);
var raster = Raster(tiff);
Assert.Empty(raster.Warnings);
Assert.Equal(14, raster.BitsPerSample);
Assert.SequenceEqual(samples, raster.Samples!);
Assert.Throws<InvalidDataException>(() => TiffImageReader.ToImageBuffer(raster));
}
[Theory]
[Case(8, 1, TiffCompression.None, false)]
[Case(8, 3, TiffCompression.Deflate, true)]
[Case(16, 3, TiffCompression.Deflate, true)]
[Case(16, 3, TiffCompression.Deflate, false)]
[Case(16, 4, TiffCompression.None, false)]
[Case(16, 1, TiffCompression.Deflate, true)]
public void WriterRoundTrips(int bits, int channels, TiffCompression compression, bool predictor)
{
const int w = 123, h = 77;
var samples = new ushort[w * h * channels];
var rng = new Random(bits + channels);
for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i % 3 == 0 ? rng.Next(1 << bits) : (i / channels * 31) & ((1 << bits) - 1));
var options = new TiffWriteOptions { BitsPerSample = bits, Compression = compression, Predictor = predictor };
using var ms = new MemoryStream();
TiffWriter.Write(ms, samples, w, h, channels, options);
var raster = Raster(ms.ToArray());
Assert.Equal(channels, raster.SamplesPerPixel);
Assert.Equal(bits, raster.BitsPerSample);
Assert.SequenceEqual(samples, raster.Samples!);
}
[Test]
public void ImageBufferRoundTripAndExifEmbedding()
{
using var image = new ImageBuffer(300, 1100);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 2) % 1000) / 999f;
}
var tiff = TiffWriter.Write(image, new TiffWriteOptions { Exif = ExifBlock() });
using var back = TiffImageReader.Decode(tiff);
for (var i = 0; i < image.Data.Length; i += 101) Assert.Approximately(image.Data[i], back.Data[i], 2e-4);
AssertExif(tiff);
Assert.True(Raster(tiff).Warnings.Count == 0);
}
[Theory]
[Case("tiff/lzw-pred.tif")]
[Case("tiff/lzw-tiled.tif")]
[Case("tiff/planar-zip.tif")]
[Case("tiff/jpeg-ycbcr.tif")]
[Case("tiff/float32-pred3.tif")]
public void FuzzedInputOnlyThrowsInvalidData(string name)
{
int ok = 0, rejected = 0;
var options = new TiffDecodeOptions { MaxSamples = 1 << 22 };
foreach (var input in Corruptions(Fixture(name), 120, seed: name.Length * 31))
{
try
{
using var image = TiffImageReader.Decode(input, options);
ok++;
}
catch (InvalidDataException)
{
rejected++;
}
}
context.Log($"{name}: {ok} decoded, {rejected} rejected");
}
internal static void Layout(TiffDirectory d, int w, int h, int spp, int bits, int compression, int rowsPerStrip = 0)
{
d.Long(TiffTags.ImageWidth, (uint)w);
d.Long(TiffTags.ImageLength, (uint)h);
d.Short(TiffTags.BitsPerSample, Enumerable.Repeat((ushort)bits, spp).ToArray());
d.Short(TiffTags.Compression, (ushort)compression);
d.Short(TiffTags.PhotometricInterpretation, spp >= 3 ? (ushort)2 : (ushort)1);
d.Short(TiffTags.SamplesPerPixel, (ushort)spp);
if (rowsPerStrip > 0) d.Long(TiffTags.RowsPerStrip, (uint)rowsPerStrip);
}
/// <summary>A big-endian Exif APP1 payload: IFD0 Make/Model/Orientation, Exif IFD (exposure, ISO, Interop), GPS IFD.</summary>
internal static byte[] ExifBlock()
{
var ms = new MemoryStream();
var w = new BinaryWriter(ms);
void U16(int v) => w.Write(BinaryPrimitives.ReverseEndianness((ushort)v));
void U32(uint v) => w.Write(BinaryPrimitives.ReverseEndianness(v));
void Entry(int tag, int type, uint count, uint value)
{
U16(tag);
U16(type);
U32(count);
U32(value);
}
w.Write("Exif\0\0MM\0*"u8);
U32(8);
// IFD0 at 8: 5 entries → 2 + 60 + 4 = 66 bytes → data area at 74.
U16(5);
Entry(0x010F, 2, 6, 74); // Make "Canon\0" at 74
Entry(0x0110, 2, 4, 0x45_4F_53_00); // Model "EOS\0" inline
Entry(0x0112, 3, 1, 6u << 16); // Orientation (not copied)
Entry(0x8769, 4, 1, 80); // Exif IFD at 80
Entry(0x8825, 4, 1, 148); // GPS IFD at 148
U32(0);
w.Write("Canon\0"u8);
// Exif IFD at 80: 3 entries → 2 + 36 + 4 = 42 → rational at 122.
U16(3);
Entry(0x829A, 5, 1, 122); // ExposureTime 1/250
Entry(0x8827, 3, 1, 400u << 16); // ISO 400
Entry(0xA005, 4, 1, 130); // Interop IFD at 130
U32(0);
U32(1);
U32(250);
// Interop IFD at 130: 2 + 12 + 4 = 18 bytes → GPS IFD at 148.
U16(1);
Entry(0x0001, 2, 4, 0x52_39_38_00); // InteroperabilityIndex "R98"
U32(0);
U16(1);
Entry(0x0001, 2, 2, 0x4E_00_00_00); // GPSLatitudeRef "N"
U32(0);
return ms.ToArray();
}
internal static void AssertExif(byte[] file)
{
var reader = TiffReader.Open(new MemoryStream(file))!;
var ifd0 = reader.ReadChain()[0];
Assert.Equal("Canon", reader.GetString(ifd0, TiffTags.Make));
Assert.Equal("EOS", reader.GetString(ifd0, TiffTags.Model));
Assert.False(ifd0.Has(TiffTags.Orientation) && reader.GetUInt(ifd0, TiffTags.Orientation) == 6, "orientation must not be copied");
var exif = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)!;
Assert.Approximately(1 / 250.0, reader.GetDouble(exif, TiffTags.ExposureTime)!.Value, 1e-9);
Assert.Equal(400u, reader.GetUInt(exif, TiffTags.IsoSpeedRatings));
var interop = reader.ReadIfd(reader.GetUInt(exif, TiffTags.InteropIfd)!.Value)!;
Assert.Equal("R98", reader.GetString(interop, 0x0001));
var gps = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.GpsIfd)!.Value)!;
Assert.Equal("N", reader.GetString(gps, TiffTags.GpsLatitudeRef));
}
}