feat(codecs): add managed JPEG decoder and pixel conversions

Baseline, extended 12-bit, progressive and lossless (SOF3) Huffman
decoding; 1/3/4 components with Adobe CMYK/YCCK; all integral sampling
factors with libjpeg fancy upsampling; restart resynchronisation;
DCT-domain scaling. Full-size blocks use a port of libjpeg's ISLOW IDCT,
so output is bit-identical to djpeg on the cjpeg fixtures.

PixelConvert maps interleaved 8/16-bit samples to linear ImageBuffers and
back, gray/RGB, Exif orientation and clamping.

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:37:15 +00:00
1 parent 800843d2ae
commit 64e4fb3df6
70 files changed
+2618

No files matched your search

@@ -0,0 +1,167 @@
using System.Text;
using Titano.Testing;
namespace Titano.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 Titano.Core.Codecs.Jpeg;
using Titano.Testing;
using static Titano.Core.Tests.Codecs.CodecTestData;
namespace Titano.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);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Regenerates the codec reference fixtures (dev-only tools: python3, libjpeg-turbo-progs, imagemagick, libtiff-tools).
# Every output is < 50 KB. Run from this directory: ./make-fixtures.sh
set -euo pipefail
cd "$(dirname "$0")"
mkdir -p jpeg png tiff
# 61x45 source (odd size exercises MCU/tile padding): gradients, colour bars, seeded noise and hard edges.
python3 - <<'EOF'
import random
W, H = 61, 45
random.seed(7)
px8, px16 = [], []
for y in range(H):
for x in range(W):
if y < 15:
r, g, b = x / (W - 1), y / 14, 1 - x / (W - 1)
elif y < 30:
bar = (x * 8) // W
r, g, b = (bar >> 2) & 1, (bar >> 1) & 1, bar & 1
r, g, b = 0.1 + 0.8 * r, 0.1 + 0.8 * g, 0.1 + 0.8 * b
else:
n = random.random()
edge = 1.0 if ((x // 3) + (y // 3)) % 2 == 0 else 0.0
r, g, b = 0.6 * edge + 0.4 * n, 0.5 * n, 0.8 * edge
px8 += [round(v * 255) for v in (r, g, b)]
px16 += [round(v * 65535) for v in (r, g, b)]
with open("src.ppm", "wb") as f:
f.write(b"P6\n%d %d\n255\n" % (W, H)); f.write(bytes(px8))
with open("src16.ppm", "wb") as f:
f.write(b"P6\n%d %d\n65535\n" % (W, H))
f.write(b"".join(v.to_bytes(2, "big") for v in px16))
EOF
# JPEG: cjpeg encodes, djpeg (accurate integer IDCT, fancy upsampling) provides the reference pixels.
for s in "444:1x1" "422:2x1" "420:2x2" "440:1x2" "411:4x1"; do
name=${s%%:*}; f=${s##*:}
cjpeg -quality 88 -sample "$f" src.ppm > "jpeg/b$name.jpg"
djpeg -ppm "jpeg/b$name.jpg" > "jpeg/b$name.ppm"
done
djpeg -nosmooth -ppm jpeg/b420.jpg > jpeg/b420-nosmooth.ppm
cjpeg -quality 85 -sample 2x2 -progressive src.ppm > jpeg/p420.jpg && djpeg -ppm jpeg/p420.jpg > jpeg/p420.ppm
cjpeg -quality 92 -sample 1x1 -progressive src.ppm > jpeg/p444.jpg && djpeg -ppm jpeg/p444.jpg > jpeg/p444.ppm
cjpeg -quality 90 -sample 2x2 -restart 1 src.ppm > jpeg/r420.jpg && djpeg -ppm jpeg/r420.jpg > jpeg/r420.ppm
cjpeg -quality 90 -sample 1x1 -restart 5B -optimize src.ppm > jpeg/r444.jpg && djpeg -ppm jpeg/r444.jpg > jpeg/r444.ppm
cjpeg -quality 90 -grayscale src.ppm > jpeg/gray.jpg && djpeg -pnm jpeg/gray.jpg > jpeg/gray.pgm
cjpeg -quality 90 -grayscale -progressive src.ppm > jpeg/pgray.jpg && djpeg -pnm jpeg/pgray.jpg > jpeg/pgray.pgm
convert src.ppm -quality 95 -colorspace CMYK jpeg/cmyk.jpg
# PNG: ImageMagick/libpng writers; pixels compare against src.ppm / src16.ppm.
convert src.ppm -interlace PNG png24:png/adam7.png
convert src16.ppm -define png:bit-depth=16 png48:png/rgb16.png
convert src16.ppm -interlace PNG -define png:bit-depth=16 png48:png/adam7-16.png
convert src.ppm -colorspace Gray -define png:color-type=0 -define png:bit-depth=8 png/gray8.png
convert src.ppm -colorspace Gray -depth 4 -define png:color-type=0 -define png:bit-depth=4 png/gray4.png
convert src.ppm -colorspace Gray -depth 2 -define png:color-type=0 -define png:bit-depth=2 png/gray2.png
convert src.ppm -colorspace Gray -threshold 50% -define png:color-type=0 -define png:bit-depth=1 png/gray1.png
convert src.ppm -colors 16 -transparent "$(convert src.ppm -colors 16 -format '%[pixel:p{0,40}]' info:)" png8:png/palette-trns.png
convert src.ppm -colors 16 -interlace PNG png8:png/palette-adam7.png
convert src.ppm -colors 12 -define png:color-type=3 -define png:bit-depth=4 png/palette4.png
convert src.ppm \( src.ppm -colorspace Gray \) -alpha off -compose CopyOpacity -composite png32:png/rgba.png
convert src.ppm -colorspace Gray \( src.ppm -channel R -separate \) -alpha off -compose CopyOpacity -composite -define png:color-type=4 png/graya.png
for f in gray1 gray2 gray4 gray8 graya palette-trns palette-adam7 palette4 rgba; do convert "png/$f.png" -depth 8 "png/$f.pam"; done
# TIFF: ImageMagick/libtiff writers in every supported layout and compression.
convert src.ppm -compress LZW -define tiff:predictor=2 tiff/lzw-pred.tif
convert src.ppm -compress RLE tiff/packbits.tif
convert src.ppm -compress None -define tiff:rows-per-strip=7 tiff/none-strips.tif
convert src16.ppm -depth 16 -compress Zip -define tiff:predictor=2 tiff/deflate16-pred.tif
convert src.ppm -compress LZW -define tiff:tile-geometry=16x16 tiff/lzw-tiled.tif
tiffcp -p separate -c zip src.ppm.tmp.tif tiff/planar-zip.tif 2>/dev/null || { convert src.ppm -compress None tiff/_tmp.tif; tiffcp -p separate -c zip tiff/_tmp.tif tiff/planar-zip.tif; rm tiff/_tmp.tif; }
convert src.ppm -compress None tiff/_tmp.tif && tiffcp -c jpeg:90 -r 16 tiff/_tmp.tif tiff/jpeg-ycbcr.tif && tiffcp -c jpeg:r:90 -r 16 tiff/_tmp.tif tiff/jpeg-rgb.tif && rm tiff/_tmp.tif
convert src16.ppm -define quantum:format=floating-point -depth 32 -compress Zip -define tiff:predictor=3 tiff/float32-pred3.tif
convert src.ppm -colorspace Gray -define tiff:photometric=min-is-white -compress None tiff/gray-miniswhite.tif
ls -l jpeg png tiff
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 241 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 308 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 685 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 920 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 727 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 691 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.