merge: managed codecs (JPEG baseline/progressive/lossless, PNG, TIFF, linear DNG, resampler)

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 10:16:18 +00:00
commit 1c09d8059a
94 files changed
+7045 -1

No files matched your search

@@ -0,0 +1,155 @@
using System.Buffers.Binary;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Imaging;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Codecs.Dng;
/// <summary>Tile compression of a linear DNG.</summary>
public enum DngCompression
{
Uncompressed = 1,
/// <summary>Lossless JPEG (SOF3, predictor 1) per tile, DNG Compression = 7.</summary>
LosslessJpeg = 7,
}
/// <summary>Options for <see cref="LinearDngWriter"/>.</summary>
public sealed record LinearDngOptions
{
public static LinearDngOptions Default { get; } = new();
public DngCompression Compression { get; init; } = DngCompression.LosslessJpeg;
/// <summary>UniqueCameraModel (and Model): raw editors key their profiles on it.</summary>
public string UniqueCameraModel { get; init; } = "Titano";
/// <summary>TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded.</summary>
public byte[]? Exif { get; init; }
/// <summary>Tile edge in pixels (multiple of 16).</summary>
public int TileSize { get; init; } = 256;
/// <summary>Worker limit for tile encoding (-1 = all cores).</summary>
public int MaxDegreeOfParallelism { get; init; } = -1;
}
/// <summary>
/// Writes linear Rec.709/sRGB-primaries RGB as a 16-bit LinearRaw DNG 1.4 that raw editors render with correct
/// colours: ColorMatrix1 = XYZ(D65) → linear sRGB, ForwardMatrix1 = linear sRGB → XYZ(D50), illuminant D65,
/// AsShotNeutral 1/1/1, WhiteLevel 65535, BaselineExposure 0. Values above 1.0 are clipped.
/// </summary>
public static class LinearDngWriter
{
/// <summary>XYZ (D65) → linear sRGB, i.e. the inverse of the sRGB → XYZ matrix (IEC 61966-2-1).</summary>
internal static readonly double[] XyzToLinearSrgb =
[
3.2404542, -1.5371385, -0.4985314,
-0.9692660, 1.8760108, 0.0415560,
0.0556434, -0.2040259, 1.0572252,
];
/// <summary>Linear sRGB → XYZ (D50), Bradford-adapted: neutral (1,1,1) maps to the D50 white point.</summary>
internal static readonly double[] LinearSrgbToXyzD50 =
[
0.4360747, 0.3850649, 0.1430804,
0.2225045, 0.7168786, 0.0606169,
0.0139322, 0.0971045, 0.7141733,
];
public static byte[] Write(ImageBuffer image, LinearDngOptions? options = null)
{
using var ms = new MemoryStream();
Write(ms, image, options);
return ms.ToArray();
}
/// <summary>Writes a linear-light buffer (gray is stored as neutral RGB; alpha is dropped).</summary>
public static void Write(Stream output, ImageBuffer image, LinearDngOptions? options = null)
{
var o = options ?? LinearDngOptions.Default;
if (o.TileSize is < 16 or > 4096 || o.TileSize % 16 != 0) throw new ArgumentOutOfRangeException(nameof(options), "Tile size must be a multiple of 16 in 16..4096");
if (!output.CanSeek)
{
using var buffer = new MemoryStream();
Write(buffer, image, o);
buffer.Position = 0;
buffer.CopyTo(output);
return;
}
int w = image.Width, h = image.Height, t = o.TileSize;
int across = (w + t - 1) / t, down = (h + t - 1) / t;
var offsets = new uint[across * down];
var counts = new uint[across * down];
var start = output.Position;
output.Write("II*\0\0\0\0\0"u8);
var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism };
var band = new ushort[w * t * 3];
var tiles = new byte[across][];
for (var ty = 0; ty < down; ty++)
{
var y0 = ty * t;
var rows = Math.Min(t, h - y0);
Parallel.For(0, rows, parallel, r => PixelConvert.EncodeRow16(image, y0 + r, band.AsSpan(r * w * 3, w * 3), 3, TransferFunction.Linear));
Parallel.For(0, across, parallel, tx => tiles[tx] = EncodeTile(band, w, rows, tx * t, t, o.Compression));
for (var tx = 0; tx < across; tx++)
{
if (output.Position - start > uint.MaxValue - (long)tiles[tx].Length) throw new InvalidOperationException("DNG exceeds 4 GB");
offsets[ty * across + tx] = (uint)(output.Position - start);
counts[ty * across + tx] = (uint)tiles[tx].Length;
output.Write(tiles[tx]);
}
}
var ifd = new TiffDirectory();
// Capture metadata first, so the source camera's Make/Model win; UniqueCameraModel still keys the profile.
if (o.Exif is { } exif) ifd.AttachExif(exif);
if (!ifd.Has(TiffTags.Make)) ifd.Ascii(TiffTags.Make, "Titano");
if (!ifd.Has(TiffTags.Model)) ifd.Ascii(TiffTags.Model, o.UniqueCameraModel);
ifd.Long(TiffTags.NewSubfileType, 0);
ifd.Long(TiffTags.ImageWidth, (uint)w);
ifd.Long(TiffTags.ImageLength, (uint)h);
ifd.Short(TiffTags.BitsPerSample, 16, 16, 16);
ifd.Short(TiffTags.Compression, (ushort)o.Compression);
ifd.Short(TiffTags.PhotometricInterpretation, 34892);
ifd.Short(TiffTags.Orientation, 1);
ifd.Short(TiffTags.SamplesPerPixel, 3);
ifd.Short(TiffTags.PlanarConfiguration, 1);
ifd.Ascii(TiffTags.Software, "Titano");
ifd.Long(TiffTags.TileWidth, (uint)t);
ifd.Long(TiffTags.TileLength, (uint)t);
ifd.Long(TiffTags.TileOffsets, offsets);
ifd.Long(TiffTags.TileByteCounts, counts);
ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0);
ifd.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0);
ifd.Ascii(TiffTags.UniqueCameraModel, o.UniqueCameraModel);
ifd.SRational(TiffTags.ColorMatrix1, Rationals(XyzToLinearSrgb));
ifd.SRational(TiffTags.ForwardMatrix1, Rationals(LinearSrgbToXyzD50));
ifd.Short(TiffTags.CalibrationIlluminant1, 21); // D65
ifd.Rational(TiffTags.AsShotNeutral, (1u, 1u), (1u, 1u), (1u, 1u));
ifd.SRational(TiffTags.BaselineExposure, (0, 1));
ifd.Long(TiffTags.WhiteLevel, 65535, 65535, 65535);
TiffWriter.WriteDirectory(output, start, ifd);
}
/// <summary>One t×t tile from a band of rows; pixels beyond the image repeat the edge (better compression).</summary>
private static byte[] EncodeTile(ushort[] band, int width, int rows, int x0, int t, DngCompression compression)
{
var tile = new ushort[t * t * 3];
for (var y = 0; y < t; y++)
{
var src = band.AsSpan(Math.Min(y, rows - 1) * width * 3, width * 3);
var dst = tile.AsSpan(y * t * 3, t * 3);
var valid = Math.Min(t, width - x0);
src.Slice(x0 * 3, valid * 3).CopyTo(dst);
for (var x = valid; x < t; x++) src.Slice((width - 1) * 3, 3).CopyTo(dst[(x * 3)..]);
}
if (compression == DngCompression.LosslessJpeg) return JpegLosslessEncoder.Encode(tile, t, t, 3, 16);
var bytes = new byte[tile.Length * 2];
for (var i = 0; i < tile.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), tile[i]);
return bytes;
}
private static (int, int)[] Rationals(double[] matrix) => matrix.Select(v => ((int)Math.Round(v * 10000), 10000)).ToArray();
}
@@ -0,0 +1,83 @@
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Jpeg;
/// <summary>
/// Managed JPEG decoder: baseline, extended (12-bit), progressive and lossless Huffman streams; 1, 3 or 4 components
/// (CMYK/YCCK via Adobe APP14); any integral sampling factors; restart intervals with resynchronisation on corrupt
/// data; DCT-domain scaling for thumbnails. Exif orientation is not applied. Malformed headers throw
/// <see cref="InvalidDataException"/>; damaged entropy-coded data yields a partial image plus warnings.
/// </summary>
public static class JpegDecoder
{
private static readonly float[]?[] LinearLuts = new float[17][];
/// <summary>Reads the frame header only (no pixel decoding).</summary>
public static JpegInfo ReadInfo(ReadOnlySpan<byte> data)
{
var parser = new JpegParser(JpegDecodeOptions.Default);
parser.Parse(data, headerOnly: true);
return parser.Info();
}
/// <summary>Decodes to interleaved gray or RGB samples (8-bit, or 16-bit containers for higher precisions).</summary>
public static JpegImage Decode(ReadOnlySpan<byte> data, JpegDecodeOptions? options = null)
{
var parser = Parse(data, options);
if (parser.Frame!.Process == JpegProcess.Lossless) return LosslessToImage(parser);
return new JpegRenderer(parser).RenderInterleaved(parser.Info());
}
/// <summary>Decodes into a linear-light <see cref="ImageBuffer"/> (samples are taken as sRGB-encoded).</summary>
/// <param name="expandGray">Return gray images as three identical channels instead of one.</param>
public static ImageBuffer DecodeToLinear(ReadOnlySpan<byte> data, JpegDecodeOptions? options = null, bool expandGray = false)
{
var parser = Parse(data, options);
if (parser.Frame!.Process == JpegProcess.Lossless)
{
var image = LosslessToImage(parser);
var channels = image.Components == 1 && expandGray ? 3 : image.Components;
return image.Pixels8 is { } p8
? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Components, outputChannels: channels)
: PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Components, maxValue: (1 << image.BitDepth) - 1, outputChannels: channels);
}
return new JpegRenderer(parser).RenderLinear(expandGray);
}
/// <summary>Decodes a TIFF/DNG tile: lossless streams return raw samples (any component count), DCT streams pixels.</summary>
internal static (JpegImage? Image, JpegLosslessImage Raw) DecodeTile(ReadOnlySpan<byte> data, JpegDecodeOptions options)
{
var parser = Parse(data, options);
return parser.Frame!.Process == JpegProcess.Lossless
? (null, JpegLosslessDecoder.Finish(parser))
: (new JpegRenderer(parser).RenderInterleaved(parser.Info()), default);
}
private static JpegParser Parse(ReadOnlySpan<byte> data, JpegDecodeOptions? options)
{
var parser = new JpegParser(options ?? JpegDecodeOptions.Default);
parser.Parse(data);
return parser;
}
private static JpegImage LosslessToImage(JpegParser parser)
{
var raw = JpegLosslessDecoder.Finish(parser);
if (raw.Components is not (1 or 3)) throw new InvalidDataException($"JPEG: {raw.Components}-component lossless images have no colour interpretation");
if (raw.Precision > 8)
return new JpegImage(parser.Info(), raw.Width, raw.Height, raw.Components, raw.Precision, null, raw.Samples, [.. parser.Warnings]);
var bytes = new byte[raw.Samples.Length];
for (var i = 0; i < bytes.Length; i++) bytes[i] = (byte)raw.Samples[i];
return new JpegImage(parser.Info(), raw.Width, raw.Height, raw.Components, 8, bytes, null, [.. parser.Warnings]);
}
/// <summary>sRGB-decoding table for codes 0..2^precision−1.</summary>
internal static float[] LinearLut(int precision)
{
if (LinearLuts[precision] is { } cached) return cached;
var size = 1 << precision;
var lut = new float[size];
for (var i = 0; i < size; i++) lut[i] = (float)ColorSpace.SrgbToLinear(i / (double)(size - 1));
return LinearLuts[precision] = lut;
}
}
+477
View File
@@ -0,0 +1,477 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Jpeg;
/// <summary>Chroma subsampling written by <see cref="JpegEncoder"/>.</summary>
public enum JpegSubsampling
{
Yuv444,
Yuv422,
Yuv420,
}
/// <summary>Options for <see cref="JpegEncoder"/>.</summary>
public sealed record JpegEncodeOptions
{
public static JpegEncodeOptions Default { get; } = new();
/// <summary>IJG quality 1–100 (scales the Annex K tables).</summary>
public int Quality { get; init; } = 90;
public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Yuv420;
/// <summary>Two-pass encoding with Huffman tables built from the image's statistics (smaller files).</summary>
public bool OptimizeHuffman { get; init; }
/// <summary>Restart interval in MCUs (0 = none).</summary>
public int RestartInterval { get; init; }
/// <summary>APP1 payloads written after SOI, each including its identifier (e.g. "Exif\0\0" + TIFF, or the XMP
/// namespace + packet); at most 65533 bytes each. When present the JFIF APP0 segment is omitted (Exif layout).</summary>
public IReadOnlyList<byte[]>? App1Segments { get; init; }
/// <summary>Ordered dither when quantising linear float input to 8-bit sRGB.</summary>
public bool Dither { get; init; }
/// <summary>Worker limit for colour conversion and forward DCT (-1 = all cores).</summary>
public int MaxDegreeOfParallelism { get; init; } = -1;
}
/// <summary>
/// Baseline JPEG encoder (8-bit, Huffman, 1 or 3 components). Colour conversion and float forward DCT run in
/// parallel per MCU row; entropy coding is sequential.
/// </summary>
public static class JpegEncoder
{
private static readonly float[] BasisT = Transpose(JpegTables.Basis);
/// <summary>Encodes a linear-light buffer (1 channel → gray JPEG, 3/4 → YCbCr; alpha is dropped).</summary>
public static byte[] Encode(ImageBuffer image, JpegEncodeOptions? options = null)
{
using var ms = new MemoryStream();
Encode(ms, image, options);
return ms.ToArray();
}
public static void Encode(Stream output, ImageBuffer image, JpegEncodeOptions? options = null)
{
var o = options ?? JpegEncodeOptions.Default;
var channels = image.Channels == 1 ? 1 : 3;
EncodeCore(output, image.Width, image.Height, channels, (y, row) => PixelConvert.EncodeRow8(image, y, row, channels, TransferFunction.Srgb, o.Dither), o);
}
/// <summary>Encodes interleaved 8-bit sRGB pixels: 1 = gray, 3 = RGB, 4 = RGBA (alpha ignored).</summary>
public static byte[] Encode(ReadOnlySpan<byte> pixels, int width, int height, int channels, JpegEncodeOptions? options = null)
{
using var ms = new MemoryStream();
Encode(ms, pixels, width, height, channels, options);
return ms.ToArray();
}
public static unsafe void Encode(Stream output, ReadOnlySpan<byte> pixels, int width, int height, int channels, JpegEncodeOptions? options = null)
{
if (channels is not (1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(channels));
if (pixels.Length < (long)width * height * channels) throw new ArgumentException("Pixel buffer too small", nameof(pixels));
var outChannels = channels == 1 ? 1 : 3;
fixed (byte* p = pixels)
{
var ptr = (nint)p;
EncodeCore(output, width, height, outChannels, (y, row) =>
{
var src = new ReadOnlySpan<byte>((byte*)ptr + (long)y * width * channels, width * channels);
if (channels == outChannels)
{
src.CopyTo(row);
return;
}
for (var x = 0; x < width; x++)
{
row[3 * x] = src[4 * x];
row[3 * x + 1] = src[4 * x + 1];
row[3 * x + 2] = src[4 * x + 2];
}
}, options ?? JpegEncodeOptions.Default);
}
}
/// <summary>IJG quality scaling of a base table (jcparam.c), clamped to baseline 1..255.</summary>
internal static int[] ScaleTable(ReadOnlySpan<byte> table, int quality)
{
quality = Math.Clamp(quality, 1, 100);
var scale = quality < 50 ? 5000 / quality : 200 - quality * 2;
var result = new int[64];
for (var i = 0; i < 64; i++) result[i] = Math.Clamp((table[i] * scale + 50) / 100, 1, 255);
return result;
}
private delegate void RowReader(int y, Span<byte> row);
private sealed class Plan
{
public required int Width, Height, Components, HY, VY, McusX, McusY;
public required int[][] Quant;
public required short[][] Coefficients;
public int BlocksPerLine(int c) => c == 0 ? McusX * HY : McusX;
}
private static void EncodeCore(Stream output, int width, int height, int components, RowReader read, JpegEncodeOptions o)
{
if (width is < 1 or > 65535 || height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width), "JPEG dimensions are 1..65535");
if (o.RestartInterval is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(o), "Restart interval is 0..65535");
var (hy, vy) = components == 1 ? (1, 1) : o.Subsampling switch
{
JpegSubsampling.Yuv444 => (1, 1),
JpegSubsampling.Yuv422 => (2, 1),
_ => (2, 2),
};
var mcusX = JpegParser.DivUp(width, 8 * hy);
var mcusY = JpegParser.DivUp(height, 8 * vy);
var plan = new Plan
{
Width = width, Height = height, Components = components, HY = hy, VY = vy, McusX = mcusX, McusY = mcusY,
Quant = [ScaleTable(JpegTables.LumaQuant, o.Quality), ScaleTable(JpegTables.ChromaQuant, o.Quality)],
Coefficients = new short[components][],
};
plan.Coefficients[0] = new short[checked(mcusX * hy * mcusY * vy * 64)];
for (var c = 1; c < components; c++) plan.Coefficients[c] = new short[checked(mcusX * mcusY * 64)];
Transform(plan, read, o.MaxDegreeOfParallelism);
JpegHuffmanCode dcY, acY, dcC, acC;
if (o.OptimizeHuffman)
{
var freq = new long[4][];
for (var i = 0; i < 4; i++) freq[i] = new long[256];
Entropy(plan, o.RestartInterval, null, freq, null);
dcY = JpegHuffmanCode.Optimal(freq[0]);
acY = JpegHuffmanCode.Optimal(freq[1]);
dcC = components > 1 ? JpegHuffmanCode.Optimal(freq[2]) : dcY;
acC = components > 1 ? JpegHuffmanCode.Optimal(freq[3]) : acY;
}
else
{
dcY = new JpegHuffmanCode(JpegTables.DcLumaBits, JpegTables.DcLumaValues);
acY = new JpegHuffmanCode(JpegTables.AcLumaBits, JpegTables.AcLumaValues);
dcC = new JpegHuffmanCode(JpegTables.DcChromaBits, JpegTables.DcChromaValues);
acC = new JpegHuffmanCode(JpegTables.AcChromaBits, JpegTables.AcChromaValues);
}
var writer = new JpegBitWriter((int)Math.Min(1 << 30, (long)width * height * components / 4));
Entropy(plan, o.RestartInterval, writer, null, [dcY, acY, dcC, acC]);
WriteHeaders(output, plan, o, dcY, acY, dcC, acC);
output.Write(writer.Written);
output.Write([0xFF, JpegTables.Eoi]);
}
/// <summary>Colour conversion, chroma downsampling (box average), forward DCT and quantisation per MCU row.</summary>
private static void Transform(Plan p, RowReader read, int parallelism)
{
int hy = p.HY, vy = p.VY, mcuH = 8 * vy, paddedW = p.McusX * 8 * hy, nc = p.Components;
var recip = new float[2][];
for (var t = 0; t < 2; t++)
{
recip[t] = new float[64];
for (var i = 0; i < 64; i++) recip[t][i] = 1f / p.Quant[t][i];
}
Parallel.For(0, p.McusY, new ParallelOptions { MaxDegreeOfParallelism = parallelism }, my =>
{
var rgb = new byte[p.Width * nc];
var planes = new float[nc][];
for (var c = 0; c < nc; c++) planes[c] = new float[paddedW * mcuH];
for (var r = 0; r < mcuH; r++)
{
var y = Math.Min(my * mcuH + r, p.Height - 1);
read(y, rgb);
var row = r * paddedW;
if (nc == 1)
{
var g = planes[0];
for (var x = 0; x < p.Width; x++) g[row + x] = rgb[x] - 128f;
}
else
{
float[] yp = planes[0], cb = planes[1], cr = planes[2];
for (var x = 0; x < p.Width; x++)
{
float rr = rgb[3 * x], gg = rgb[3 * x + 1], bb = rgb[3 * x + 2];
yp[row + x] = 0.299f * rr + 0.587f * gg + 0.114f * bb - 128f;
cb[row + x] = -0.168736f * rr - 0.331264f * gg + 0.5f * bb;
cr[row + x] = 0.5f * rr - 0.418688f * gg - 0.081312f * bb;
}
}
for (var c = 0; c < nc; c++)
{
var plane = planes[c];
plane.AsSpan(row + p.Width, paddedW - p.Width).Fill(plane[row + p.Width - 1]);
}
}
Span<float> block = stackalloc float[64];
Span<float> coef = stackalloc float[64];
var bpl = p.BlocksPerLine(0);
for (var by = 0; by < vy; by++)
{
for (var bx = 0; bx < bpl; bx++)
{
for (var r = 0; r < 8; r++) planes[0].AsSpan((by * 8 + r) * paddedW + bx * 8, 8).CopyTo(block.Slice(r * 8, 8));
ForwardDct(block, coef);
Quantize(coef, recip[0], p.Coefficients[0].AsSpan(((my * vy + by) * bpl + bx) * 64, 64));
}
}
var area = 1f / (hy * vy);
for (var c = 1; c < nc; c++)
{
var plane = planes[c];
for (var bx = 0; bx < p.McusX; bx++)
{
for (var r = 0; r < 8; r++)
{
for (var i = 0; i < 8; i++)
{
var sum = 0f;
var x0 = (bx * 8 + i) * hy;
for (var dy = 0; dy < vy; dy++)
{
var at = (r * vy + dy) * paddedW + x0;
for (var dx = 0; dx < hy; dx++) sum += plane[at + dx];
}
block[r * 8 + i] = sum * area;
}
}
ForwardDct(block, coef);
Quantize(coef, recip[1], p.Coefficients[c].AsSpan((my * p.McusX + bx) * 64, 64));
}
}
});
}
/// <summary>F = B·f·Bᵀ with the orthonormal basis (DC = 8 × mean), Vector256 rows when available.</summary>
private static void ForwardDct(ReadOnlySpan<float> f, Span<float> output)
{
var basis = JpegTables.Basis;
if (Vector256.IsHardwareAccelerated)
{
ref var bt = ref MemoryMarshal.GetArrayDataReference(BasisT);
Span<Vector256<float>> t = stackalloc Vector256<float>[8];
for (var y = 0; y < 8; y++)
{
var acc = Vector256<float>.Zero;
for (var x = 0; x < 8; x++) acc += Vector256.Create(f[y * 8 + x]) * Vector256.LoadUnsafe(ref bt, (nuint)(x * 8));
t[y] = acc;
}
for (var v = 0; v < 8; v++)
{
var acc = Vector256<float>.Zero;
for (var y = 0; y < 8; y++) acc += Vector256.Create(basis[v * 8 + y]) * t[y];
acc.CopyTo(output.Slice(v * 8, 8));
}
return;
}
Span<float> tmp = stackalloc float[64];
for (var y = 0; y < 8; y++)
{
for (var u = 0; u < 8; u++)
{
var s = 0f;
for (var x = 0; x < 8; x++) s += f[y * 8 + x] * basis[u * 8 + x];
tmp[y * 8 + u] = s;
}
}
for (var v = 0; v < 8; v++)
{
for (var u = 0; u < 8; u++)
{
var s = 0f;
for (var y = 0; y < 8; y++) s += basis[v * 8 + y] * tmp[y * 8 + u];
output[v * 8 + u] = s;
}
}
}
private static void Quantize(ReadOnlySpan<float> coef, float[] recip, Span<short> destination)
{
destination[0] = (short)Math.Clamp(MathF.Round(coef[0] * recip[0]), -1024f, 1023f);
for (var i = 1; i < 64; i++) destination[i] = (short)Math.Clamp(MathF.Round(coef[i] * recip[i]), -1023f, 1023f);
}
/// <summary>Walks every MCU in order: counts symbol frequencies (<paramref name="freq"/>) or emits codes.</summary>
private static void Entropy(Plan p, int restartInterval, JpegBitWriter? writer, long[][]? freq, JpegHuffmanCode[]? codes)
{
var preds = new int[p.Components];
var total = p.McusX * p.McusY;
var rst = 0;
for (var mcu = 0; mcu < total; mcu++)
{
if (restartInterval > 0 && mcu > 0 && mcu % restartInterval == 0)
{
Array.Clear(preds);
if (writer is not null)
{
writer.Flush();
writer.WriteMarker((byte)(JpegTables.Rst0 + rst));
}
rst = (rst + 1) & 7;
}
writer?.Reserve(4096);
int mx = mcu % p.McusX, my = mcu / p.McusX;
for (var c = 0; c < p.Components; c++)
{
int h = c == 0 ? p.HY : 1, v = c == 0 ? p.VY : 1, bpl = p.BlocksPerLine(c), table = c == 0 ? 0 : 2;
for (var by = 0; by < v; by++)
{
for (var bx = 0; bx < h; bx++)
{
var block = p.Coefficients[c].AsSpan(((my * v + by) * bpl + mx * h + bx) * 64, 64);
if (writer is null) CountBlock(block, ref preds[c], freq![table], freq[table + 1]);
else EncodeBlock(writer, block, ref preds[c], codes![table], codes[table + 1]);
}
}
}
}
writer?.Flush();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Category(int v) => v == 0 ? 0 : 32 - BitOperations.LeadingZeroCount((uint)Math.Abs(v));
private static void CountBlock(ReadOnlySpan<short> block, ref int pred, long[] dc, long[] ac)
{
dc[Category(block[0] - pred)]++;
pred = block[0];
var run = 0;
var order = JpegTables.NaturalOrder;
for (var k = 1; k < 64; k++)
{
int v = block[order[k]];
if (v == 0)
{
run++;
continue;
}
for (; run >= 16; run -= 16) ac[0xF0]++;
ac[run << 4 | Category(v)]++;
run = 0;
}
if (run > 0) ac[0]++;
}
private static void EncodeBlock(JpegBitWriter w, ReadOnlySpan<short> block, ref int pred, JpegHuffmanCode dc, JpegHuffmanCode ac)
{
var diff = block[0] - pred;
pred = block[0];
var s = Category(diff);
w.Write((uint)(dc.Code[s] << s | ((diff < 0 ? diff - 1 : diff) & ((1 << s) - 1))), dc.Length[s] + s);
var run = 0;
var order = JpegTables.NaturalOrder;
for (var k = 1; k < 64; k++)
{
int v = block[order[k]];
if (v == 0)
{
run++;
continue;
}
for (; run >= 16; run -= 16) w.Write(ac.Code[0xF0], ac.Length[0xF0]);
s = Category(v);
var symbol = run << 4 | s;
w.Write((uint)(ac.Code[symbol] << s | ((v < 0 ? v - 1 : v) & ((1 << s) - 1))), ac.Length[symbol] + s);
run = 0;
}
if (run > 0) w.Write(ac.Code[0], ac.Length[0]);
}
private static void WriteHeaders(Stream output, Plan p, JpegEncodeOptions o, JpegHuffmanCode dcY, JpegHuffmanCode acY, JpegHuffmanCode dcC, JpegHuffmanCode acC)
{
var h = new MemoryStream();
h.Write([0xFF, JpegTables.Soi]);
if (o.App1Segments is { Count: > 0 } apps)
{
foreach (var app in apps)
{
if (app.Length > 65533) throw new ArgumentException("APP1 payload exceeds 65533 bytes", nameof(o));
Segment(h, JpegTables.App1, app);
}
}
else
{
Segment(h, JpegTables.App0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
}
var tables = p.Components == 1 ? 1 : 2;
var dqt = new byte[65 * tables];
for (var t = 0; t < tables; t++)
{
dqt[65 * t] = (byte)t;
for (var k = 0; k < 64; k++) dqt[65 * t + 1 + k] = (byte)p.Quant[t][JpegTables.NaturalOrder[k]];
}
Segment(h, JpegTables.Dqt, dqt);
var sof = new byte[6 + 3 * p.Components];
sof[0] = 8;
sof[1] = (byte)(p.Height >> 8);
sof[2] = (byte)p.Height;
sof[3] = (byte)(p.Width >> 8);
sof[4] = (byte)p.Width;
sof[5] = (byte)p.Components;
for (var c = 0; c < p.Components; c++)
{
sof[6 + 3 * c] = (byte)(c + 1);
sof[7 + 3 * c] = c == 0 ? (byte)(p.HY << 4 | p.VY) : (byte)0x11;
sof[8 + 3 * c] = (byte)(c == 0 ? 0 : 1);
}
Segment(h, JpegTables.Sof0, sof);
var dht = new MemoryStream();
Huffman(dht, 0x00, dcY);
Huffman(dht, 0x10, acY);
if (p.Components > 1)
{
Huffman(dht, 0x01, dcC);
Huffman(dht, 0x11, acC);
}
Segment(h, JpegTables.Dht, dht.ToArray());
if (o.RestartInterval > 0) Segment(h, JpegTables.Dri, [(byte)(o.RestartInterval >> 8), (byte)o.RestartInterval]);
var sos = new byte[4 + 2 * p.Components];
sos[0] = (byte)p.Components;
for (var c = 0; c < p.Components; c++)
{
sos[1 + 2 * c] = (byte)(c + 1);
sos[2 + 2 * c] = c == 0 ? (byte)0x00 : (byte)0x11;
}
sos[^3] = 0;
sos[^2] = 63;
sos[^1] = 0;
Segment(h, JpegTables.Sos, sos);
h.Position = 0;
h.CopyTo(output);
}
private static void Huffman(Stream s, byte classAndId, JpegHuffmanCode code)
{
s.WriteByte(classAndId);
s.Write(code.Bits);
s.Write(code.Values);
}
internal static void Segment(Stream s, byte marker, ReadOnlySpan<byte> payload)
{
var length = payload.Length + 2;
s.Write([0xFF, marker, (byte)(length >> 8), (byte)length]);
s.Write(payload);
}
private static float[] Transpose(float[] m)
{
var t = new float[64];
for (var i = 0; i < 8; i++)
{
for (var j = 0; j < 8; j++) t[j * 8 + i] = m[i * 8 + j];
}
return t;
}
}
+272
View File
@@ -0,0 +1,272 @@
using System.Runtime.CompilerServices;
namespace Titano.Core.Codecs.Jpeg;
/// <summary>Canonical Huffman decoding table with a 9-bit lookahead (and a combined run/value table for AC).</summary>
internal sealed class JpegHuffmanTable
{
public const int FastBits = 9;
/// <summary><c>(length &lt;&lt; 8) | symbol</c> for codes of ≤ <see cref="FastBits"/> bits; 0 = longer code.</summary>
public readonly ushort[] Fast = new ushort[1 << FastBits];
/// <summary>Exclusive upper bound of each code length's codes, left-aligned to 16 bits.</summary>
public readonly int[] MaxCode = new int[18];
/// <summary>Symbol index = (code &gt;&gt; (16 − length)) + Delta[length].</summary>
public readonly int[] Delta = new int[17];
public readonly byte[] Values = new byte[256];
/// <summary>For AC tables: <c>(value &lt;&lt; 16) | (run &lt;&lt; 8) | totalBits</c> when code and magnitude fit in the lookahead.</summary>
public readonly int[] FastAc = new int[1 << FastBits];
/// <summary>Builds a table from the 16 code-length counts and the symbols (DHT layout).</summary>
/// <exception cref="InvalidDataException">The lengths oversubscribe the code space.</exception>
public JpegHuffmanTable(ReadOnlySpan<byte> counts, ReadOnlySpan<byte> values)
{
int code = 0, k = 0;
for (var len = 1; len <= 16; len++)
{
Delta[len] = k - code;
for (var i = 0; i < counts[len - 1]; i++, code++, k++)
{
if (code >= 1 << len) throw new InvalidDataException("JPEG: Huffman table oversubscribed");
if (len > FastBits) continue;
var first = code << (FastBits - len);
Fast.AsSpan(first, 1 << (FastBits - len)).Fill((ushort)(len << 8 | values[k]));
}
MaxCode[len] = code << (16 - len);
code <<= 1;
}
MaxCode[17] = int.MaxValue;
values[..k].CopyTo(Values);
BuildFastAc();
}
private void BuildFastAc()
{
for (var i = 0; i < Fast.Length; i++)
{
int e = Fast[i];
if (e == 0) continue;
var len = e >> 8;
var rs = e & 0xFF;
int run = rs >> 4, s = rs & 15;
if (s == 0 || len + s > FastBits) continue;
var m = (i >> (FastBits - len - s)) & ((1 << s) - 1);
var v = m < 1 << (s - 1) ? m - (1 << s) + 1 : m;
FastAc[i] = v << 16 | run << 8 | (len + s);
}
}
}
/// <summary>Thrown inside a scan when entropy-coded data is corrupt; the scan decoder resynchronises.</summary>
internal sealed class JpegEntropyException(string message) : Exception(message);
/// <summary>
/// MSB-first bit reader over entropy-coded JPEG data: removes 0xFF00 stuffing, stops at markers and then
/// feeds zero bits, counting them so that consumption past the real data is detectable (<see cref="Overrun"/>).
/// </summary>
internal ref struct JpegBitReader
{
private readonly ReadOnlySpan<byte> _data;
private int _pos;
private ulong _bits;
private int _count;
private int _padBits;
private int _marker;
private int _markerPos;
public JpegBitReader(ReadOnlySpan<byte> data, int start)
{
_data = data;
_pos = start;
}
/// <summary>Marker code that stopped the reader (0 = none, -1 = end of data).</summary>
public readonly int Marker => _marker;
/// <summary>True once bits beyond the entropy-coded segment have been consumed.</summary>
public readonly bool Overrun => _padBits > _count;
/// <summary>Where marker parsing continues after the scan.</summary>
public readonly int Position => _marker > 0 ? _markerPos : _pos;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Ensure(int n)
{
if (_count < n) Fill();
}
/// <summary>Next <paramref name="n"/> bits (1..32) without consuming; call <see cref="Ensure"/> first.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int Peek(int n) => (int)(_bits >> (64 - n));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Consume(int n)
{
_bits <<= n;
_count -= n;
}
/// <summary>Reads 1..16 bits.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadBits(int n)
{
if (_count < n) Fill();
var v = (int)(_bits >> (64 - n));
_bits <<= n;
_count -= n;
return v;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadBit()
{
if (_count < 1) Fill();
var v = (int)(_bits >> 63);
_bits <<= 1;
_count--;
return v;
}
/// <summary>Reads an <paramref name="s"/>-bit magnitude (1..16) and sign-extends it (T.81 F.2.2.1 EXTEND).</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Receive(int s)
{
var v = ReadBits(s);
return v + ((((v >> (s - 1)) & 1) - 1) & (1 - (1 << s)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Decode(JpegHuffmanTable t)
{
if (_count < 16) Fill();
int e = t.Fast[(int)(_bits >> (64 - JpegHuffmanTable.FastBits))];
if (e != 0)
{
var len = e >> 8;
_bits <<= len;
_count -= len;
return e & 0xFF;
}
return DecodeSlow(t);
}
private int DecodeSlow(JpegHuffmanTable t)
{
var code = (int)(_bits >> 48);
for (var len = JpegHuffmanTable.FastBits + 1; len <= 16; len++)
{
if (code < t.MaxCode[len])
{
Consume(len);
return t.Values[(code >> (16 - len)) + t.Delta[len]];
}
}
throw new JpegEntropyException("JPEG: invalid Huffman code");
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Fill()
{
while (_count <= 56)
{
if (_marker != 0 || _pos >= _data.Length)
{
if (_marker == 0) _marker = -1;
_padBits += 8;
_count += 8;
continue;
}
int b = _data[_pos];
if (b == 0xFF)
{
var p = _pos + 1;
while (p < _data.Length && _data[p] == 0xFF) p++;
if (p >= _data.Length)
{
_pos = p;
continue;
}
if (_data[p] != 0)
{
_marker = _data[p];
_markerPos = p - 1;
continue;
}
_pos = p + 1;
}
else
{
_pos++;
}
_bits |= (ulong)(uint)b << (56 - _count);
_count += 8;
}
}
/// <summary>Discards buffered bits and locates the next marker (for restart processing). Returns its code
/// (-1 when the data ends) without consuming it; <see cref="AcceptMarker"/> steps over it.</summary>
public int FindMarker()
{
_bits = 0;
_count = 0;
_padBits = 0;
if (_marker > 0) return _marker;
var p = _pos;
while (p + 1 < _data.Length)
{
if (_data[p] == 0xFF && _data[p + 1] is not (0x00 or 0xFF))
{
_marker = _data[p + 1];
_markerPos = p;
return _marker;
}
p++;
}
_pos = _data.Length;
_marker = -1;
return -1;
}
/// <summary>Consumes the marker found by <see cref="FindMarker"/> and resumes reading after it.</summary>
public void AcceptMarker()
{
if (_marker <= 0) return;
_pos = _markerPos + 2;
_marker = 0;
}
/// <summary>
/// Restart processing with libjpeg's resync_to_restart rules: skips invalid markers and stale RSTs, accepts the
/// expected RSTn, and reports how many whole intervals were lost when RSTn+1/RSTn+2 shows up instead.
/// Returns false when a non-restart marker (or the end of data) ends the scan.
/// </summary>
public bool NextRestart(ref int expected, out int lostIntervals)
{
lostIntervals = 0;
while (true)
{
var marker = FindMarker();
if (marker < 0) return false;
if (marker < 0xC0)
{
AcceptMarker(); // corrupt data that happened to look like a marker
continue;
}
if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) return false;
var delta = (marker - JpegTables.Rst0 - expected) & 7;
if (delta is 6 or 7)
{
AcceptMarker(); // a restart we already passed
continue;
}
if (delta is 1 or 2) lostIntervals = delta;
AcceptMarker();
expected = (marker - JpegTables.Rst0 + 1) & 7;
return true;
}
}
}
@@ -0,0 +1,151 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>Huffman code table for encoding (code and length per symbol) plus its DHT representation.</summary>
internal sealed class JpegHuffmanCode
{
public readonly byte[] Bits;
public readonly byte[] Values;
public readonly ushort[] Code = new ushort[256];
public readonly byte[] Length = new byte[256];
public JpegHuffmanCode(ReadOnlySpan<byte> bits, ReadOnlySpan<byte> values)
{
Bits = bits.ToArray();
Values = values.ToArray();
int code = 0, k = 0;
for (var len = 1; len <= 16; len++)
{
for (var i = 0; i < bits[len - 1]; i++, k++, code++)
{
Code[values[k]] = (ushort)code;
Length[values[k]] = (byte)len;
}
code <<= 1;
}
}
/// <summary>Optimal length-limited (16-bit) table for symbol frequencies (T.81 Annex K.2, as libjpeg).</summary>
public static JpegHuffmanCode Optimal(ReadOnlySpan<long> frequencies)
{
var freq = new long[257];
frequencies.CopyTo(freq);
freq[256] = 1; // reserved code point guarantees no all-ones code
var codeSize = new int[257];
var others = new int[257];
Array.Fill(others, -1);
while (true)
{
int c1 = -1, c2 = -1;
long v1 = long.MaxValue, v2 = long.MaxValue;
for (var i = 0; i <= 256; i++)
{
if (freq[i] != 0 && freq[i] <= v1)
{
v1 = freq[i];
c1 = i;
}
}
for (var i = 0; i <= 256; i++)
{
if (freq[i] != 0 && freq[i] <= v2 && i != c1)
{
v2 = freq[i];
c2 = i;
}
}
if (c2 < 0) break;
freq[c1] += freq[c2];
freq[c2] = 0;
codeSize[c1]++;
while (others[c1] >= 0)
{
c1 = others[c1];
codeSize[c1]++;
}
others[c1] = c2;
codeSize[c2]++;
while (others[c2] >= 0)
{
c2 = others[c2];
codeSize[c2]++;
}
}
var bits = new int[33];
for (var i = 0; i <= 256; i++)
{
if (codeSize[i] > 0) bits[codeSize[i]]++;
}
for (var i = 32; i > 16; i--)
{
while (bits[i] > 0)
{
var j = i - 2;
while (bits[j] == 0) j--;
bits[i] -= 2;
bits[i - 1]++;
bits[j + 1] += 2;
bits[j]--;
}
}
var top = 16;
while (bits[top] == 0) top--;
bits[top]--; // drop the reserved symbol
var counts = new byte[16];
for (var i = 1; i <= 16; i++) counts[i - 1] = (byte)bits[i];
var values = new List<byte>();
for (var len = 1; len <= 32; len++)
{
for (var s = 0; s < 256; s++)
{
if (codeSize[s] == len) values.Add((byte)s);
}
}
return new JpegHuffmanCode(counts, values.ToArray());
}
}
/// <summary>MSB-first bit writer with 0xFF byte stuffing into a growable buffer.</summary>
internal sealed class JpegBitWriter(int initialCapacity)
{
private byte[] _buffer = new byte[Math.Max(1024, initialCapacity)];
private int _length;
private ulong _acc;
private int _bits;
public ReadOnlySpan<byte> Written => _buffer.AsSpan(0, _length);
/// <summary>Guarantees room for <paramref name="bytes"/> more output bytes (stuffing included).</summary>
public void Reserve(int bytes)
{
if (_length + bytes <= _buffer.Length) return;
Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + bytes));
}
/// <summary>Appends the low <paramref name="size"/> bits of <paramref name="value"/> (size ≤ 32).</summary>
public void Write(uint value, int size)
{
_acc = (_acc << size) | (value & (uint)((1UL << size) - 1));
_bits += size;
while (_bits >= 8)
{
_bits -= 8;
var b = (byte)(_acc >> _bits);
_buffer[_length++] = b;
if (b == 0xFF) _buffer[_length++] = 0;
}
}
/// <summary>Pads the last byte with 1-bits (T.81 F.1.2.3).</summary>
public void Flush()
{
if (_bits > 0) Write((1u << (8 - _bits)) - 1, 8 - _bits);
_acc = 0;
}
public void WriteMarker(byte marker)
{
Reserve(2);
_buffer[_length++] = 0xFF;
_buffer[_length++] = marker;
}
}
+169
View File
@@ -0,0 +1,169 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>
/// Inverse DCT. Full-size blocks use libjpeg's accurate integer algorithm (jidctint ISLOW: Loeffler–Ligtenberg–
/// Moschytz with 13-bit constants), so output is bit-identical to libjpeg/djpeg. Reduced sizes (4, 2, 1) evaluate
/// the low-frequency n×n coefficients on an n-point grid in float (DCT-domain scaling for thumbnails).
/// </summary>
internal static class JpegIdct
{
private const int ConstBits = 13;
private const int Fix0298631336 = 2446, Fix0390180644 = 3196, Fix0541196100 = 4433, Fix0765366865 = 6270;
private const int Fix0899976223 = 7373, Fix1175875602 = 9633, Fix1501321110 = 12299, Fix1847759065 = 15137;
private const int Fix1961570560 = 16069, Fix2053119869 = 16819, Fix2562915447 = 20995, Fix3072711026 = 25172;
private static readonly float[] Basis4 = JpegTables.BuildBasis(4);
private static readonly float[] Basis2 = JpegTables.BuildBasis(2);
/// <summary>Transforms one block into n·n samples, level-shifted and clamped to 0..2^precision−1.</summary>
/// <param name="coefficients">64 quantised coefficients, natural order.</param>
/// <param name="quant">64 dequantisation factors, natural order.</param>
/// <param name="size">Output block size: 8, 4, 2 or 1.</param>
/// <param name="precision">Sample precision (8 or 12).</param>
public static void Transform(ReadOnlySpan<short> coefficients, ReadOnlySpan<int> quant, int size, int precision, Span<int> output)
{
var max = (1 << precision) - 1;
var center = 1 << (precision - 1);
if (size == 8)
{
Islow(coefficients, quant, precision == 8 ? 2 : 1, center, max, output);
return;
}
if (size == 1)
{
output[0] = Math.Clamp((int)MathF.Round(coefficients[0] * quant[0] * 0.125f) + center, 0, max);
return;
}
Reduced(coefficients, quant, size, size == 4 ? Basis4 : Basis2, center, max, output);
}
/// <summary>Port of libjpeg-turbo jpeg_idct_islow (columns, then rows; PASS1_BITS 2 for 8-bit, 1 for 12-bit).</summary>
private static void Islow(ReadOnlySpan<short> c, ReadOnlySpan<int> q, int pass1Bits, int center, int max, Span<int> output)
{
Span<int> ws = stackalloc int[64];
_ = c[63];
_ = q[63];
for (var col = 0; col < 8; col++)
{
if (c[8 + col] == 0 && c[16 + col] == 0 && c[24 + col] == 0 && c[32 + col] == 0 &&
c[40 + col] == 0 && c[48 + col] == 0 && c[56 + col] == 0)
{
var dc = c[col] * q[col] << pass1Bits;
for (var r = 0; r < 8; r++) ws[r * 8 + col] = dc;
continue;
}
var shift = ConstBits - pass1Bits;
Butterfly(
c[col] * q[col], c[8 + col] * q[8 + col], c[16 + col] * q[16 + col], c[24 + col] * q[24 + col],
c[32 + col] * q[32 + col], c[40 + col] * q[40 + col], c[48 + col] * q[48 + col], c[56 + col] * q[56 + col],
out var o0, out var o1, out var o2, out var o3, out var o4, out var o5, out var o6, out var o7);
var round = 1 << (shift - 1);
ws[col] = (o0 + round) >> shift;
ws[8 + col] = (o1 + round) >> shift;
ws[16 + col] = (o2 + round) >> shift;
ws[24 + col] = (o3 + round) >> shift;
ws[32 + col] = (o4 + round) >> shift;
ws[40 + col] = (o5 + round) >> shift;
ws[48 + col] = (o6 + round) >> shift;
ws[56 + col] = (o7 + round) >> shift;
}
for (var row = 0; row < 8; row++)
{
var w = ws.Slice(row * 8, 8);
var o = output.Slice(row * 8, 8);
if (w[1] == 0 && w[2] == 0 && w[3] == 0 && w[4] == 0 && w[5] == 0 && w[6] == 0 && w[7] == 0)
{
var dcShift = pass1Bits + 3;
o.Fill(Math.Clamp(((w[0] + (1 << (dcShift - 1))) >> dcShift) + center, 0, max));
continue;
}
var shift = ConstBits + pass1Bits + 3;
var round = 1 << (shift - 1);
Butterfly(w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7],
out var o0, out var o1, out var o2, out var o3, out var o4, out var o5, out var o6, out var o7);
o[0] = Math.Clamp(((o0 + round) >> shift) + center, 0, max);
o[1] = Math.Clamp(((o1 + round) >> shift) + center, 0, max);
o[2] = Math.Clamp(((o2 + round) >> shift) + center, 0, max);
o[3] = Math.Clamp(((o3 + round) >> shift) + center, 0, max);
o[4] = Math.Clamp(((o4 + round) >> shift) + center, 0, max);
o[5] = Math.Clamp(((o5 + round) >> shift) + center, 0, max);
o[6] = Math.Clamp(((o6 + round) >> shift) + center, 0, max);
o[7] = Math.Clamp(((o7 + round) >> shift) + center, 0, max);
}
}
/// <summary>One 8-point ISLOW pass; outputs are scaled by 2^13 (CONST_BITS) before descaling.</summary>
private static void Butterfly(int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7,
out int o0, out int o1, out int o2, out int o3, out int o4, out int o5, out int o6, out int o7)
{
// Even part: the rotator is sqrt(2)·c(−6).
var z1 = (i2 + i6) * Fix0541196100;
var tmp2 = z1 - i6 * Fix1847759065;
var tmp3 = z1 + i2 * Fix0765366865;
var tmp0 = (i0 + i4) << ConstBits;
var tmp1 = (i0 - i4) << ConstBits;
int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
// Odd part (figure 8 of the LL&M paper).
tmp0 = i7;
tmp1 = i5;
tmp2 = i3;
tmp3 = i1;
z1 = tmp0 + tmp3;
var z2 = tmp1 + tmp2;
var z3 = tmp0 + tmp2;
var z4 = tmp1 + tmp3;
var z5 = (z3 + z4) * Fix1175875602;
tmp0 *= Fix0298631336;
tmp1 *= Fix2053119869;
tmp2 *= Fix3072711026;
tmp3 *= Fix1501321110;
z1 *= -Fix0899976223;
z2 *= -Fix2562915447;
z3 = z3 * -Fix1961570560 + z5;
z4 = z4 * -Fix0390180644 + z5;
tmp0 += z1 + z3;
tmp1 += z2 + z4;
tmp2 += z2 + z3;
tmp3 += z1 + z4;
o0 = tmp10 + tmp3;
o7 = tmp10 - tmp3;
o1 = tmp11 + tmp2;
o6 = tmp11 - tmp2;
o2 = tmp12 + tmp1;
o5 = tmp12 - tmp1;
o3 = tmp13 + tmp0;
o4 = tmp13 - tmp0;
}
/// <summary>n-point IDCT of the low-frequency n×n coefficients, evaluated at the centres of n output samples.</summary>
private static void Reduced(ReadOnlySpan<short> coefficients, ReadOnlySpan<int> quant, int n, float[] basis, int center, int max, Span<int> output)
{
Span<float> g = stackalloc float[n * n];
Span<float> f = stackalloc float[n];
g.Clear();
for (var v = 0; v < n; v++)
{
var row = g.Slice(v * n, n);
for (var u = 0; u < n; u++)
{
int coef = coefficients[v * 8 + u];
if (coef == 0) continue;
var value = (float)(coef * quant[v * 8 + u]);
for (var x = 0; x < n; x++) row[x] += value * basis[u * n + x];
}
}
for (var y = 0; y < n; y++)
{
f.Clear();
for (var v = 0; v < n; v++)
{
var w = basis[v * n + y];
var row = g.Slice(v * n, n);
for (var x = 0; x < n; x++) f[x] += w * row[x];
}
for (var x = 0; x < n; x++) output[y * n + x] = Math.Clamp((int)MathF.Round(f[x]) + center, 0, max);
}
}
}
@@ -0,0 +1,132 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>
/// Lossless JPEG (SOF3, ITU T.81 Annex H) as used by DNG raw tiles and CR2: predictors 1–7, point transform,
/// 2–16 bit precision, one or more components (interleaved or in separate scans), restart intervals.
/// </summary>
public static class JpegLosslessDecoder
{
/// <summary>Decodes a lossless stream to interleaved samples with the frame's own width and component count
/// (DNG tiles often encode e.g. two components at half the tile width; callers re-map the sample order).</summary>
/// <exception cref="InvalidDataException">The stream is malformed or not lossless.</exception>
public static JpegLosslessImage Decode(ReadOnlySpan<byte> data)
{
var parser = new JpegParser(JpegDecodeOptions.Default);
parser.Parse(data);
if (parser.Frame!.Process != JpegProcess.Lossless) throw new InvalidDataException("JPEG: not a lossless (SOF3) stream");
return Finish(parser);
}
/// <summary>Applies each component's point transform and packages the samples.</summary>
internal static JpegLosslessImage Finish(JpegParser parser)
{
var f = parser.Frame!;
var n = f.Components.Length;
var samples = parser.LosslessSamples ?? new ushort[checked(f.Width * f.Height * n)];
foreach (var c in f.Components)
{
if (c.PointTransform == 0) continue;
for (var i = c.Index; i < samples.Length; i += n) samples[i] = (ushort)(samples[i] << c.PointTransform);
c.PointTransform = 0;
}
parser.LosslessSamples = samples;
return new JpegLosslessImage(samples, f.Width, f.Height, n, f.Precision);
}
internal static int DecodeScan(JpegParser parser, ReadOnlySpan<byte> data, int pos, JpegScan scan)
{
var f = parser.Frame!;
int width = f.Width, nf = f.Components.Length, stride = width * nf;
var samples = parser.LosslessSamples ??= new ushort[checked(stride * f.Height)];
var comps = scan.Components;
var tables = scan.DcTables;
var ns = comps.Length;
var index = new int[ns];
for (var i = 0; i < ns; i++)
{
index[i] = comps[i].Index;
comps[i].PointTransform = scan.Al;
}
var predictor = scan.Ss;
var initial = 1 << (f.Precision - scan.Al - 1);
var interval = parser.RestartInterval;
var total = (long)width * f.Height;
var reader = new JpegBitReader(data, pos);
long mcu = 0;
int x = 0, y = 0, restartRow = 0, expectedRst = 0;
var first = true;
while (mcu < total)
{
var end = interval > 0 ? Math.Min(total, mcu + interval) : total;
try
{
for (; mcu < end; mcu++)
{
var at = y * stride + x * nf;
for (var i = 0; i < ns; i++)
{
var s = reader.Decode(tables[i]!);
var diff = s switch
{
0 => 0,
16 => 32768,
> 16 => throw new JpegEntropyException("JPEG: bad lossless difference magnitude"),
_ => reader.Receive(s),
};
var idx = at + index[i];
int pred;
if (first) pred = initial;
else if (y == restartRow) pred = samples[idx - nf];
else if (x == 0) pred = samples[idx - stride];
else pred = Predict(predictor, samples[idx - nf], samples[idx - stride], samples[idx - stride - nf]);
samples[idx] = (ushort)(pred + diff);
}
first = false;
if (++x == width)
{
x = 0;
y++;
if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data");
}
}
if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data");
}
catch (JpegEntropyException ex)
{
parser.Warn(ex.Message);
if (interval == 0) break;
mcu = end;
}
if (mcu >= total || interval == 0) break;
if (!reader.NextRestart(ref expectedRst, out var lost))
{
parser.Warn("JPEG: restart marker missing; scan truncated");
break;
}
if (lost > 0)
{
// Intervals between the expected and the found marker were lost: leave their samples untouched.
parser.Warn($"JPEG: {lost} restart interval(s) lost");
mcu += (long)lost * interval;
}
x = (int)(mcu % width);
y = (int)(mcu / width);
restartRow = y;
first = true;
}
return reader.Position;
}
private static int Predict(int predictor, int ra, int rb, int rc) => predictor switch
{
1 => ra,
2 => rb,
3 => rc,
4 => ra + rb - rc,
5 => ra + ((rb - rc) >> 1),
6 => rb + ((ra - rc) >> 1),
_ => (ra + rb) >> 1,
};
}
@@ -0,0 +1,169 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>
/// Lossless JPEG (SOF3) encoder: one interleaved scan, optimal Huffman table per component, predictors 1–7,
/// point transform and restart intervals. Used for DNG tiles (DNG Compression = 7).
/// </summary>
public static class JpegLosslessEncoder
{
/// <summary>Encodes interleaved samples (each &lt; 2^<paramref name="precision"/>).</summary>
/// <param name="restartInterval">Restart interval in samples per component (0 = none).</param>
public static byte[] Encode(ReadOnlySpan<ushort> samples, int width, int height, int components, int precision,
int predictor = 1, int pointTransform = 0, int restartInterval = 0)
{
if (width is < 1 or > 65535 || height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width));
if (components is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(components));
if (precision is < 2 or > 16) throw new ArgumentOutOfRangeException(nameof(precision));
if (predictor is < 1 or > 7) throw new ArgumentOutOfRangeException(nameof(predictor));
if (pointTransform < 0 || pointTransform >= precision) throw new ArgumentOutOfRangeException(nameof(pointTransform));
if (restartInterval is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(restartInterval));
if (samples.Length < (long)width * height * components) throw new ArgumentException("Sample buffer too small", nameof(samples));
var limit = 1 << precision;
foreach (var s in samples[..(width * height * components)])
{
if (s >= limit) throw new ArgumentException($"Sample {s} exceeds {precision}-bit precision", nameof(samples));
}
var layout = new Layout(width, height, components, predictor, pointTransform, restartInterval, precision);
var counter = new Counter { Frequencies = new long[components][] };
for (var c = 0; c < components; c++) counter.Frequencies[c] = new long[256];
Walk(samples, layout, ref counter);
var codes = new JpegHuffmanCode[components];
for (var c = 0; c < components; c++) codes[c] = JpegHuffmanCode.Optimal(counter.Frequencies[c]);
var emitter = new Emitter { Writer = new JpegBitWriter((int)Math.Min(1 << 30, (long)width * height * components)), Codes = codes };
Walk(samples, layout, ref emitter);
emitter.Writer.Flush();
using var output = new MemoryStream();
output.Write([0xFF, JpegTables.Soi]);
var sof = new byte[6 + 3 * components];
sof[0] = (byte)precision;
sof[1] = (byte)(height >> 8);
sof[2] = (byte)height;
sof[3] = (byte)(width >> 8);
sof[4] = (byte)width;
sof[5] = (byte)components;
for (var c = 0; c < components; c++)
{
sof[6 + 3 * c] = (byte)(c + 1);
sof[7 + 3 * c] = 0x11;
}
JpegEncoder.Segment(output, JpegTables.Sof3, sof);
var dht = new MemoryStream();
for (var c = 0; c < components; c++)
{
dht.WriteByte((byte)c);
dht.Write(codes[c].Bits);
dht.Write(codes[c].Values);
}
JpegEncoder.Segment(output, JpegTables.Dht, dht.ToArray());
if (restartInterval > 0) JpegEncoder.Segment(output, JpegTables.Dri, [(byte)(restartInterval >> 8), (byte)restartInterval]);
var sos = new byte[4 + 2 * components];
sos[0] = (byte)components;
for (var c = 0; c < components; c++)
{
sos[1 + 2 * c] = (byte)(c + 1);
sos[2 + 2 * c] = (byte)(c << 4);
}
sos[^3] = (byte)predictor;
sos[^2] = 0;
sos[^1] = (byte)pointTransform;
JpegEncoder.Segment(output, JpegTables.Sos, sos);
output.Write(emitter.Writer.Written);
output.Write([0xFF, JpegTables.Eoi]);
return output.ToArray();
}
private readonly record struct Layout(int Width, int Height, int Components, int Predictor, int PointTransform, int RestartInterval, int Precision);
private interface ISink
{
void Difference(int component, int diff);
void Restart(int index);
}
/// <summary>Visits every residual in stream order with the decoder's prediction rules (T.81 H.1.2).</summary>
private static void Walk<TSink>(ReadOnlySpan<ushort> samples, Layout l, ref TSink sink) where TSink : struct, ISink
{
int w = l.Width, nc = l.Components, stride = w * nc, pt = l.PointTransform;
var initial = 1 << (l.Precision - pt - 1);
var total = (long)w * l.Height;
int restartRow = 0, x = 0, y = 0, rst = 0;
var first = true;
for (long mcu = 0; mcu < total; mcu++)
{
if (l.RestartInterval > 0 && mcu > 0 && mcu % l.RestartInterval == 0)
{
sink.Restart(rst);
rst = (rst + 1) & 7;
first = true;
restartRow = y;
}
var at = y * stride + x * nc;
for (var c = 0; c < nc; c++)
{
var idx = at + c;
int pred;
if (first) pred = initial;
else if (y == restartRow) pred = samples[idx - nc] >> pt;
else if (x == 0) pred = samples[idx - stride] >> pt;
else
{
int ra = samples[idx - nc] >> pt, rb = samples[idx - stride] >> pt, rc = samples[idx - stride - nc] >> pt;
pred = l.Predictor switch
{
1 => ra,
2 => rb,
3 => rc,
4 => ra + rb - rc,
5 => ra + ((rb - rc) >> 1),
6 => rb + ((ra - rc) >> 1),
_ => (ra + rb) >> 1,
};
}
sink.Difference(c, (short)((samples[idx] >> pt) - pred));
}
first = false;
if (++x == w)
{
x = 0;
y++;
}
}
}
private static int Category(int diff) => diff == -32768 ? 16 : diff == 0 ? 0 : 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)Math.Abs(diff));
private struct Counter : ISink
{
public long[][] Frequencies;
public readonly void Difference(int component, int diff) => Frequencies[component][Category(diff)]++;
public readonly void Restart(int index)
{
}
}
private struct Emitter : ISink
{
public JpegBitWriter Writer;
public JpegHuffmanCode[] Codes;
public readonly void Difference(int component, int diff)
{
var code = Codes[component];
var s = Category(diff);
Writer.Reserve(16);
Writer.Write(code.Code[s], code.Length[s]);
if (s is > 0 and < 16) Writer.Write((uint)((diff < 0 ? diff - 1 : diff) & ((1 << s) - 1)), s);
}
public readonly void Restart(int index)
{
Writer.Flush();
Writer.WriteMarker((byte)(JpegTables.Rst0 + index));
}
}
}
+400
View File
@@ -0,0 +1,400 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>One frame component and its coefficient (DCT) storage.</summary>
internal sealed class JpegComponent
{
public int Id, Index, H, V, QuantTable;
/// <summary>Component size in samples: ceil(X·H/Hmax) × ceil(Y·V/Vmax).</summary>
public int Width, Height;
/// <summary>Blocks covering the component (non-interleaved scan extent).</summary>
public int WidthInBlocks, HeightInBlocks;
/// <summary>Allocated block grid, padded to whole MCUs.</summary>
public int BlocksPerLine, BlocksPerColumn;
/// <summary>Quantised coefficients, 64 per block in natural order, blocks row-major.</summary>
public short[]? Coefficients;
/// <summary>Quantisation table latched when the component's first scan starts (natural order).</summary>
public ushort[]? Quant;
/// <summary>Point transform of the lossless scan that carried this component.</summary>
public int PointTransform;
public int DcPred;
}
/// <summary>Frame header (SOFn) with derived MCU geometry.</summary>
internal sealed class JpegFrame
{
public required JpegProcess Process { get; init; }
public required int Precision { get; init; }
public required int Width { get; init; }
public required int Height { get; init; }
public required JpegComponent[] Components { get; init; }
public int HMax { get; init; }
public int VMax { get; init; }
public int McusX { get; init; }
public int McusY { get; init; }
}
/// <summary>Scan header (SOS) resolved against the frame.</summary>
internal sealed class JpegScan
{
public required JpegComponent[] Components { get; init; }
public required JpegHuffmanTable?[] DcTables { get; init; }
public required JpegHuffmanTable?[] AcTables { get; init; }
public int Ss { get; init; }
public int Se { get; init; }
public int Ah { get; init; }
public int Al { get; init; }
}
/// <summary>
/// Marker-level JPEG parser: tables, frame and scan headers; dispatches entropy-coded segments to the DCT or
/// lossless scan decoders. Structural errors throw <see cref="InvalidDataException"/>; once a scan has been
/// decoded, later errors only end parsing with a warning so that partial images survive.
/// </summary>
internal sealed class JpegParser(JpegDecodeOptions options)
{
private readonly ushort[]?[] _quant = new ushort[4][];
private readonly JpegHuffmanTable?[] _dc = new JpegHuffmanTable[4];
private readonly JpegHuffmanTable?[] _ac = new JpegHuffmanTable[4];
private readonly List<string> _warnings = [];
private static JpegHuffmanTable? _stdDcLuma, _stdDcChroma, _stdAcLuma, _stdAcChroma;
public JpegDecodeOptions Options { get; } = options;
public JpegFrame? Frame { get; private set; }
public int RestartInterval { get; private set; }
public int AdobeTransform { get; private set; } = -1;
public bool Jfif { get; private set; }
public int ScansDecoded { get; private set; }
public IReadOnlyList<string> Warnings => _warnings;
/// <summary>Interleaved samples of a lossless frame (point transform not yet applied).</summary>
public ushort[]? LosslessSamples { get; set; }
public void Warn(string message)
{
if (_warnings.Count < 64) _warnings.Add(message);
}
/// <summary>Parses a full stream. With <paramref name="headerOnly"/> it stops at the first scan header.</summary>
public void Parse(ReadOnlySpan<byte> data, bool headerOnly = false)
{
if (Options.Tables is { Length: > 0 } tables) ParseCore(tables, tablesOnly: true, headerOnly: false);
try
{
ParseCore(data, tablesOnly: false, headerOnly);
}
catch (InvalidDataException ex) when (ScansDecoded > 0)
{
Warn(ex.Message);
}
if (Frame is null) throw new InvalidDataException("JPEG: no frame header");
if (!headerOnly && ScansDecoded == 0) throw new InvalidDataException("JPEG: no scan data");
}
public JpegInfo Info()
{
var f = Frame ?? throw new InvalidDataException("JPEG: no frame header");
return new JpegInfo(
f.Width, f.Height, f.Components.Length, f.Precision, f.Process, ColorSpace(),
f.Components.Select(c => (c.H, c.V)).ToArray(), RestartInterval);
}
/// <summary>Colour space after applying the option override and libjpeg's marker/component-id heuristics.</summary>
public JpegColorSpace ColorSpace()
{
var f = Frame!;
var n = f.Components.Length;
if (n == 1) return JpegColorSpace.Gray;
if (f.Process == JpegProcess.Lossless && Options.ColorTransform == JpegColorTransform.Auto)
return n switch { 3 => JpegColorSpace.Rgb, 4 => JpegColorSpace.Cmyk, _ => JpegColorSpace.Other };
var transformed = Options.ColorTransform switch
{
JpegColorTransform.None => false,
JpegColorTransform.YCbCr => true,
_ => n == 3
? Jfif || (AdobeTransform < 0 ? !(f.Components[0].Id == 'R' && f.Components[1].Id == 'G' && f.Components[2].Id == 'B') : AdobeTransform != 0)
: AdobeTransform == 2,
};
return n switch
{
3 => transformed ? JpegColorSpace.YCbCr : JpegColorSpace.Rgb,
4 => transformed ? JpegColorSpace.Ycck : JpegColorSpace.Cmyk,
_ => JpegColorSpace.Other,
};
}
private void ParseCore(ReadOnlySpan<byte> data, bool tablesOnly, bool headerOnly)
{
if (data.Length < 4 || data[0] != 0xFF || data[1] != JpegTables.Soi) throw new InvalidDataException("JPEG: missing SOI marker");
var pos = 2;
while (true)
{
var marker = NextMarker(data, ref pos);
if (marker < 0)
{
if (!tablesOnly) Warn("JPEG: missing EOI marker");
return;
}
if (marker == JpegTables.Eoi) return;
if (marker is JpegTables.Soi or (>= JpegTables.Rst0 and <= JpegTables.Rst0 + 7) or 0x01) continue;
if (pos + 2 > data.Length) throw new InvalidDataException("JPEG: truncated marker segment");
var length = data[pos] << 8 | data[pos + 1];
if (length < 2 || pos + length > data.Length) throw new InvalidDataException($"JPEG: bad length for marker 0x{marker:X2}");
var segment = data.Slice(pos + 2, length - 2);
pos += length;
switch (marker)
{
case JpegTables.Dqt:
ParseDqt(segment);
break;
case JpegTables.Dht:
ParseDht(segment);
break;
case JpegTables.Dri:
if (segment.Length < 2) throw new InvalidDataException("JPEG: bad DRI");
RestartInterval = segment[0] << 8 | segment[1];
break;
case JpegTables.App0:
if (segment.StartsWith("JFIF\0"u8)) Jfif = true;
break;
case JpegTables.App14:
if (segment.Length >= 12 && segment.StartsWith("Adobe"u8)) AdobeTransform = segment[11];
break;
case >= JpegTables.Sof0 and <= JpegTables.Sof3:
if (tablesOnly) throw new InvalidDataException("JPEG: frame header in a tables-only stream");
if (Frame is not null) throw new InvalidDataException("JPEG: more than one frame");
ParseSof(marker, segment);
break;
case JpegTables.Sos:
if (tablesOnly || Frame is null) throw new InvalidDataException("JPEG: scan without frame header");
if (headerOnly) return;
pos = DecodeScan(data, segment, pos);
ScansDecoded++;
break;
case JpegTables.Dac:
throw new InvalidDataException("JPEG: arithmetic coding is not supported");
case >= 0xC5 and <= 0xCF:
throw new InvalidDataException($"JPEG: unsupported coding process (SOF 0x{marker:X2})");
}
}
}
/// <summary>Finds the next marker at or after <paramref name="pos"/>, skipping garbage; returns its code or -1.</summary>
private int NextMarker(ReadOnlySpan<byte> data, ref int pos)
{
var start = pos;
while (pos + 1 < data.Length)
{
if (data[pos] != 0xFF)
{
pos++;
continue;
}
int m = data[pos + 1];
if (m == 0xFF)
{
pos++;
continue;
}
if (m == 0)
{
pos += 2;
continue;
}
if (pos != start) Warn($"JPEG: {pos - start} extraneous bytes before marker 0x{m:X2}");
pos += 2;
return m;
}
pos = data.Length;
return -1;
}
private void ParseDqt(ReadOnlySpan<byte> s)
{
while (s.Length > 0)
{
int pq = s[0] >> 4, tq = s[0] & 15;
var size = pq == 0 ? 64 : 128;
if (pq > 1 || tq > 3 || s.Length < 1 + size) throw new InvalidDataException("JPEG: bad DQT");
var table = new ushort[64];
for (var k = 0; k < 64; k++)
{
table[JpegTables.NaturalOrder[k]] = pq == 0 ? s[1 + k] : (ushort)(s[1 + 2 * k] << 8 | s[2 + 2 * k]);
}
_quant[tq] = table;
s = s[(1 + size)..];
}
}
private void ParseDht(ReadOnlySpan<byte> s)
{
while (s.Length > 0)
{
if (s.Length < 17) throw new InvalidDataException("JPEG: bad DHT");
int tc = s[0] >> 4, th = s[0] & 15;
if (tc > 1 || th > 3) throw new InvalidDataException("JPEG: bad DHT class/id");
var counts = s.Slice(1, 16);
var total = 0;
foreach (var c in counts) total += c;
if (total > 256 || s.Length < 17 + total) throw new InvalidDataException("JPEG: bad DHT counts");
var table = new JpegHuffmanTable(counts, s.Slice(17, total));
(tc == 0 ? _dc : _ac)[th] = table;
s = s[(17 + total)..];
}
}
private void ParseSof(int marker, ReadOnlySpan<byte> s)
{
if (s.Length < 6) throw new InvalidDataException("JPEG: bad SOF");
var process = marker switch
{
JpegTables.Sof0 => JpegProcess.Baseline,
JpegTables.Sof1 => JpegProcess.ExtendedSequential,
JpegTables.Sof2 => JpegProcess.Progressive,
_ => JpegProcess.Lossless,
};
int precision = s[0], height = s[1] << 8 | s[2], width = s[3] << 8 | s[4], n = s[5];
if (process == JpegProcess.Lossless ? precision is < 2 or > 16 : precision is not (8 or 12))
throw new InvalidDataException($"JPEG: unsupported precision {precision}");
if (width == 0 || height == 0) throw new InvalidDataException("JPEG: zero image size (DNL is not supported)");
if ((long)width * height > Options.MaxPixels) throw new InvalidDataException($"JPEG: {width}x{height} exceeds the pixel limit");
if (n is < 1 or > 4 || s.Length < 6 + 3 * n) throw new InvalidDataException("JPEG: bad component count");
var components = new JpegComponent[n];
int hMax = 1, vMax = 1;
for (var i = 0; i < n; i++)
{
var c = s.Slice(6 + 3 * i, 3);
int h = c[1] >> 4, v = c[1] & 15;
if (h is < 1 or > 4 || v is < 1 or > 4 || c[2] > 3) throw new InvalidDataException("JPEG: bad sampling factors");
components[i] = new JpegComponent { Id = c[0], Index = i, H = h, V = v, QuantTable = c[2] };
hMax = Math.Max(hMax, h);
vMax = Math.Max(vMax, v);
}
if (n == 1)
{
// A single component is always coded non-interleaved: its own factors are irrelevant.
components[0].H = components[0].V = hMax = vMax = 1;
}
foreach (var c in components)
{
if (hMax % c.H != 0 || vMax % c.V != 0) throw new InvalidDataException("JPEG: fractional sampling ratios are not supported");
if (process == JpegProcess.Lossless && (c.H != 1 || c.V != 1))
throw new InvalidDataException("JPEG: subsampled lossless streams are not supported");
}
var unit = process == JpegProcess.Lossless ? 1 : 8;
var mcusX = DivUp(width, unit * hMax);
var mcusY = DivUp(height, unit * vMax);
foreach (var c in components)
{
c.Width = DivUp(width * c.H, hMax);
c.Height = DivUp(height * c.V, vMax);
c.WidthInBlocks = DivUp(c.Width, 8);
c.HeightInBlocks = DivUp(c.Height, 8);
c.BlocksPerLine = mcusX * c.H;
c.BlocksPerColumn = mcusY * c.V;
}
Frame = new JpegFrame
{
Process = process, Precision = precision, Width = width, Height = height, Components = components,
HMax = hMax, VMax = vMax, McusX = mcusX, McusY = mcusY,
};
}
private int DecodeScan(ReadOnlySpan<byte> data, ReadOnlySpan<byte> s, int pos)
{
var frame = Frame!;
if (s.Length < 1) throw new InvalidDataException("JPEG: bad SOS");
int n = s[0];
if (n is < 1 or > 4 || s.Length < 4 + 2 * n) throw new InvalidDataException("JPEG: bad SOS component count");
var comps = new JpegComponent[n];
var dc = new JpegHuffmanTable?[n];
var ac = new JpegHuffmanTable?[n];
var tdTa = new int[n];
for (var i = 0; i < n; i++)
{
int id = s[1 + 2 * i];
JpegComponent? match = null;
foreach (var c in frame.Components)
{
if (c.Id == id && Array.IndexOf(comps, c) < 0)
{
match = c;
break;
}
}
comps[i] = match ?? throw new InvalidDataException($"JPEG: scan references unknown component {id}");
tdTa[i] = s[2 + 2 * i];
}
var p = 1 + 2 * n;
int ss = s[p], se = s[p + 1], ah = s[p + 2] >> 4, al = s[p + 2] & 15;
if (frame.Process == JpegProcess.Lossless)
{
if (ss is < 1 or > 7) throw new InvalidDataException($"JPEG: bad lossless predictor {ss}");
if (al >= frame.Precision) throw new InvalidDataException("JPEG: bad point transform");
for (var i = 0; i < n; i++) dc[i] = _dc[tdTa[i] >> 4 & 3] ?? throw new InvalidDataException("JPEG: missing Huffman table");
var losslessScan = new JpegScan { Components = comps, DcTables = dc, AcTables = ac, Ss = ss, Al = al };
return JpegLosslessDecoder.DecodeScan(this, data, pos, losslessScan);
}
var progressive = frame.Process == JpegProcess.Progressive;
if (progressive)
{
if (ss > se || se > 63 || (ss == 0 && se != 0) || (ss > 0 && n != 1) || al > 13 || ah > 13)
throw new InvalidDataException("JPEG: bad progressive scan parameters");
}
else
{
ss = 0;
se = 63;
ah = al = 0;
}
if (n > 1)
{
var blocks = 0;
foreach (var c in comps) blocks += c.H * c.V;
if (blocks > 10) throw new InvalidDataException("JPEG: too many blocks per MCU");
}
var needDc = ss == 0 && ah == 0;
var needAc = se > 0;
for (var i = 0; i < n; i++)
{
int td = tdTa[i] >> 4, ta = tdTa[i] & 15;
if (td > 3 || ta > 3) throw new InvalidDataException("JPEG: bad Huffman table selector");
if (needDc) dc[i] = _dc[td] ?? StandardTable(dc: true, td);
if (needAc) ac[i] = _ac[ta] ?? StandardTable(dc: false, ta);
var c = comps[i];
if (c.Quant is null)
{
c.Quant = _quant[c.QuantTable] is { } q ? (ushort[])q.Clone() : throw new InvalidDataException("JPEG: missing quantisation table");
}
c.Coefficients ??= new short[checked(c.BlocksPerLine * c.BlocksPerColumn * 64)];
}
var scan = new JpegScan { Components = comps, DcTables = dc, AcTables = ac, Ss = ss, Se = se, Ah = ah, Al = al };
return JpegScanDecoder.Decode(this, data, pos, scan);
}
/// <summary>Quantisation table for a component that never appeared in a scan (rendered flat).</summary>
public ushort[] QuantFor(JpegComponent c) => c.Quant ?? _quant[c.QuantTable] ?? new ushort[64];
/// <summary>Annex K tables for streams that omit DHT (Motion-JPEG), as libjpeg does.</summary>
private static JpegHuffmanTable StandardTable(bool dc, int id)
{
if (id > 1) throw new InvalidDataException("JPEG: missing Huffman table");
return (dc, id) switch
{
(true, 0) => _stdDcLuma ??= new JpegHuffmanTable(JpegTables.DcLumaBits, JpegTables.DcLumaValues),
(true, _) => _stdDcChroma ??= new JpegHuffmanTable(JpegTables.DcChromaBits, JpegTables.DcChromaValues),
(false, 0) => _stdAcLuma ??= new JpegHuffmanTable(JpegTables.AcLumaBits, JpegTables.AcLumaValues),
_ => _stdAcChroma ??= new JpegHuffmanTable(JpegTables.AcChromaBits, JpegTables.AcChromaValues),
};
}
internal static int DivUp(int a, int b) => (int)(((long)a + b - 1) / b);
}
+378
View File
@@ -0,0 +1,378 @@
using System.Buffers;
using System.Numerics;
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Jpeg;
/// <summary>
/// Turns decoded coefficients into pixels: (A) parallel IDCT of every block into per-component sample planes,
/// (B) parallel bands of rows doing chroma upsampling (libjpeg "fancy" triangle filters for 2× factors,
/// replication otherwise) and colour conversion (libjpeg's fixed-point YCbCr tables, CMYK/YCCK → RGB).
/// </summary>
internal sealed class JpegRenderer
{
private const int BandRows = 16;
private readonly JpegParser _parser;
private readonly JpegFrame _frame;
private readonly int _n;
private readonly bool _fancy;
private readonly int _max;
private readonly JpegColorSpace _colorSpace;
private readonly bool _invertedCmyk;
private readonly ParallelOptions _parallel;
private readonly byte[]?[] _planes8;
private readonly ushort[]?[] _planes16;
private readonly int[] _stride, _validW, _validH, _hf, _vf;
public JpegRenderer(JpegParser parser)
{
_parser = parser;
_frame = parser.Frame!;
var options = parser.Options;
_n = BlockSize(_frame, options.MaxLongEdge);
_fancy = options.FancyUpsampling;
_max = (1 << _frame.Precision) - 1;
_colorSpace = parser.ColorSpace();
_invertedCmyk = parser.AdobeTransform >= 0 || _colorSpace == JpegColorSpace.Ycck;
_parallel = new ParallelOptions { MaxDegreeOfParallelism = options.MaxDegreeOfParallelism };
Width = JpegParser.DivUp(_frame.Width * _n, 8);
Height = JpegParser.DivUp(_frame.Height * _n, 8);
Channels = _colorSpace == JpegColorSpace.Gray ? 1 : 3;
if (_colorSpace == JpegColorSpace.Other) throw new InvalidDataException("JPEG: component count has no colour interpretation");
var count = _frame.Components.Length;
_planes8 = new byte[count][];
_planes16 = new ushort[count][];
_stride = new int[count];
_validW = new int[count];
_validH = new int[count];
_hf = new int[count];
_vf = new int[count];
for (var i = 0; i < count; i++)
{
var c = _frame.Components[i];
_hf[i] = _frame.HMax / c.H;
_vf[i] = _frame.VMax / c.V;
_validW[i] = JpegParser.DivUp(_frame.Width * c.H * _n, _frame.HMax * 8);
_validH[i] = JpegParser.DivUp(_frame.Height * c.V * _n, _frame.VMax * 8);
}
}
public int Width { get; }
public int Height { get; }
/// <summary>Output channels: 1 for gray, 3 otherwise.</summary>
public int Channels { get; }
/// <summary>IDCT output size per block (8 = full size, 4/2/1 = DCT-domain scaling) for a requested long edge.</summary>
public static int BlockSize(JpegFrame frame, int maxLongEdge)
{
if (maxLongEdge <= 0) return 8;
var longEdge = Math.Max(frame.Width, frame.Height);
foreach (var n in (ReadOnlySpan<int>)[1, 2, 4])
{
if (JpegParser.DivUp(longEdge * n, 8) >= maxLongEdge) return n;
}
return 8;
}
public JpegImage RenderInterleaved(JpegInfo info)
{
RunIdct();
var length = checked(Width * Height * Channels);
if (_frame.Precision <= 8)
{
var pixels = new byte[length];
Render((y, rows) =>
{
var dst = pixels.AsSpan(y * Width * Channels, Width * Channels);
for (var c = 0; c < Channels; c++)
{
var src = rows[c];
for (var x = 0; x < Width; x++) dst[x * Channels + c] = (byte)src[x];
}
});
return new JpegImage(info, Width, Height, Channels, 8, pixels, null, [.. _parser.Warnings]);
}
var pixels16 = new ushort[length];
Render((y, rows) =>
{
var dst = pixels16.AsSpan(y * Width * Channels, Width * Channels);
for (var c = 0; c < Channels; c++)
{
var src = rows[c];
for (var x = 0; x < Width; x++) dst[x * Channels + c] = (ushort)src[x];
}
});
return new JpegImage(info, Width, Height, Channels, _frame.Precision, null, pixels16, [.. _parser.Warnings]);
}
/// <summary>Renders straight into linear-light float planes (sRGB transfer removed by table lookup).</summary>
public ImageBuffer RenderLinear(bool expandGray)
{
RunIdct();
var lut = _frame.Precision == 8 ? null : JpegDecoder.LinearLut(_frame.Precision);
var outChannels = Channels == 1 && !expandGray ? 1 : 3;
var image = new ImageBuffer(Width, Height, outChannels, clear: false);
var storage = image.Storage;
var plane = image.PlaneLength;
Render((y, rows) =>
{
for (var c = 0; c < outChannels; c++)
{
var src = rows[Channels == 1 ? 0 : c];
var dst = storage.AsSpan(c * plane + y * Width, Width);
if (lut is null)
{
for (var x = 0; x < dst.Length; x++) dst[x] = ColorSpace.Linear8((byte)src[x]);
}
else
{
for (var x = 0; x < dst.Length; x++) dst[x] = lut[src[x]];
}
}
});
return image;
}
private void RunIdct()
{
var comps = _frame.Components;
var center = 1 << (_frame.Precision - 1);
var jobs = new List<(int Component, int BlockRow)>();
for (var i = 0; i < comps.Length; i++)
{
var c = comps[i];
_stride[i] = c.BlocksPerLine * _n;
var length = checked(_stride[i] * c.BlocksPerColumn * _n);
if (_frame.Precision <= 8) _planes8[i] = new byte[length];
else _planes16[i] = new ushort[length];
var blockRows = JpegParser.DivUp(_validH[i], _n);
for (var by = 0; by < blockRows; by++) jobs.Add((i, by));
}
var quant = new int[comps.Length][];
for (var i = 0; i < comps.Length; i++) quant[i] = Array.ConvertAll(_parser.QuantFor(comps[i]), q => (int)q);
Parallel.For(0, jobs.Count, _parallel, () => new int[64], (j, _, block) =>
{
var (i, by) = jobs[j];
var c = comps[i];
var stride = _stride[i];
var rowOffset = by * _n * stride;
if (c.Coefficients is not { } coefficients)
{
// Component never scanned: flat mid-grey, like zero coefficients.
if (_planes8[i] is { } flat8) flat8.AsSpan(rowOffset, _n * stride).Fill((byte)center);
else _planes16[i].AsSpan(rowOffset, _n * stride).Fill((ushort)center);
return block;
}
var blocks = JpegParser.DivUp(_validW[i], _n);
for (var bx = 0; bx < blocks; bx++)
{
JpegIdct.Transform(coefficients.AsSpan((by * c.BlocksPerLine + bx) * 64, 64), quant[i], _n, _frame.Precision, block);
var at = rowOffset + bx * _n;
for (var y = 0; y < _n; y++, at += stride)
{
var src = block.AsSpan(y * _n, _n);
if (_planes8[i] is { } p8)
{
var dst = p8.AsSpan(at, _n);
for (var x = 0; x < _n; x++) dst[x] = (byte)src[x];
}
else
{
var dst = _planes16[i].AsSpan(at, _n);
for (var x = 0; x < _n; x++) dst[x] = (ushort)src[x];
}
}
}
return block;
}, _ => { });
foreach (var c in comps) c.Coefficients = null;
}
private delegate void RowSink(int y, int[][] rows);
private void Render(RowSink sink)
{
var bands = JpegParser.DivUp(Height, BandRows);
var count = _frame.Components.Length;
var ycc = _colorSpace is JpegColorSpace.YCbCr or JpegColorSpace.Ycck ? YccTables.For(_frame.Precision) : null;
Parallel.For(0, bands, _parallel, band =>
{
var rows = new int[count][];
for (var c = 0; c < count; c++) rows[c] = ArrayPool<int>.Shared.Rent(Width + 1);
try
{
var end = Math.Min(Height, (band + 1) * BandRows);
for (var y = band * BandRows; y < end; y++)
{
for (var c = 0; c < count; c++)
{
if (_planes8[c] is { } p8) Upsample(p8, c, y, rows[c]);
else Upsample(_planes16[c]!, c, y, rows[c]);
}
ConvertColor(rows, ycc);
sink(y, rows);
}
}
finally
{
foreach (var r in rows) ArrayPool<int>.Shared.Return(r);
}
});
}
/// <summary>Writes one output row of component <paramref name="c"/> at full output width. <paramref name="dst"/>
/// holds at least <c>Width + 1</c> values, enough for the 2·w samples a 2× upsampler produces.</summary>
private void Upsample<T>(T[] plane, int c, int y, int[] dst) where T : unmanaged, IBinaryInteger<T>
{
int hf = _hf[c], vf = _vf[c], stride = _stride[c], w = _validW[c], h = _validH[c];
var cy = Math.Min(y / vf, h - 1);
var near = plane.AsSpan(cy * stride, w);
var width = Width;
if (hf == 1 && vf == 1)
{
for (var x = 0; x < width; x++) dst[x] = int.CreateTruncating(near[x]);
return;
}
if (_fancy && vf == 2 && hf <= 2)
{
var upper = (y & 1) == 0;
var far = plane.AsSpan(Math.Clamp(upper ? cy - 1 : cy + 1, 0, h - 1) * stride, w);
if (hf == 1)
{
var bias = upper ? 1 : 2;
for (var x = 0; x < width; x++) dst[x] = (3 * int.CreateTruncating(near[x]) + int.CreateTruncating(far[x]) + bias) >> 2;
return;
}
if (w > 2)
{
H2V2(near, far, w, dst);
return;
}
}
if (_fancy && hf == 2 && vf == 1 && w > 2)
{
H2V1(near, w, dst);
return;
}
for (var x = 0; x < width; x++) dst[x] = int.CreateTruncating(near[x / hf]);
}
/// <summary>libjpeg h2v1_fancy_upsample: 3/4·nearer + 1/4·further, alternating rounding bias.</summary>
private static void H2V1<T>(ReadOnlySpan<T> s, int w, Span<int> o) where T : unmanaged, IBinaryInteger<T>
{
var first = int.CreateTruncating(s[0]);
o[0] = first;
o[1] = (3 * first + int.CreateTruncating(s[1]) + 2) >> 2;
for (var i = 1; i < w - 1; i++)
{
var v = 3 * int.CreateTruncating(s[i]);
o[2 * i] = (v + int.CreateTruncating(s[i - 1]) + 1) >> 2;
o[2 * i + 1] = (v + int.CreateTruncating(s[i + 1]) + 2) >> 2;
}
var last = int.CreateTruncating(s[w - 1]);
o[2 * w - 2] = (3 * last + int.CreateTruncating(s[w - 2]) + 1) >> 2;
o[2 * w - 1] = last;
}
/// <summary>libjpeg h2v2_fancy_upsample: triangle filter in both directions (9/3/3/1 weights).</summary>
private static void H2V2<T>(ReadOnlySpan<T> near, ReadOnlySpan<T> far, int w, Span<int> o) where T : unmanaged, IBinaryInteger<T>
{
var thisSum = 3 * int.CreateTruncating(near[0]) + int.CreateTruncating(far[0]);
var nextSum = 3 * int.CreateTruncating(near[1]) + int.CreateTruncating(far[1]);
o[0] = (thisSum * 4 + 8) >> 4;
o[1] = (thisSum * 3 + nextSum + 7) >> 4;
var lastSum = thisSum;
thisSum = nextSum;
for (var i = 1; i < w - 1; i++)
{
nextSum = 3 * int.CreateTruncating(near[i + 1]) + int.CreateTruncating(far[i + 1]);
o[2 * i] = (thisSum * 3 + lastSum + 8) >> 4;
o[2 * i + 1] = (thisSum * 3 + nextSum + 7) >> 4;
lastSum = thisSum;
thisSum = nextSum;
}
o[2 * w - 2] = (thisSum * 3 + lastSum + 8) >> 4;
o[2 * w - 1] = (thisSum * 4 + 7) >> 4;
}
private void ConvertColor(int[][] rows, YccTables? ycc)
{
var w = Width;
var max = _max;
switch (_colorSpace)
{
case JpegColorSpace.YCbCr:
YccToRgb(rows, ycc!, w, max);
break;
case JpegColorSpace.Cmyk or JpegColorSpace.Ycck:
{
if (_colorSpace == JpegColorSpace.Ycck)
{
YccToRgb(rows, ycc!, w, max);
for (var c = 0; c < 3; c++)
{
var r = rows[c];
for (var x = 0; x < w; x++) r[x] = max - r[x];
}
}
var k = rows[3];
var half = max / 2;
for (var c = 0; c < 3; c++)
{
var r = rows[c];
for (var x = 0; x < w; x++)
{
r[x] = _invertedCmyk ? (r[x] * k[x] + half) / max : ((max - r[x]) * (max - k[x]) + half) / max;
}
}
break;
}
}
}
private static void YccToRgb(int[][] rows, YccTables t, int w, int max)
{
int[] y = rows[0], cb = rows[1], cr = rows[2];
for (var x = 0; x < w; x++)
{
int yy = y[x], b = cb[x], r = cr[x];
y[x] = Math.Clamp(yy + t.CrR[r], 0, max);
cb[x] = Math.Clamp(yy + ((t.CbG[b] + t.CrG[r]) >> 16), 0, max);
cr[x] = Math.Clamp(yy + t.CbB[b], 0, max);
}
}
/// <summary>libjpeg's fixed-point (16 fractional bits) YCbCr → RGB tables for a sample precision.</summary>
private sealed class YccTables
{
private static readonly YccTables?[] Cache = new YccTables?[17];
public readonly int[] CrR, CbB, CrG, CbG;
private YccTables(int precision)
{
var size = 1 << precision;
var center = size / 2;
CrR = new int[size];
CbB = new int[size];
CrG = new int[size];
CbG = new int[size];
const int half = 1 << 15;
for (var i = 0; i < size; i++)
{
var x = i - center;
CrR[i] = (Fix(1.40200) * x + half) >> 16;
CbB[i] = (Fix(1.77200) * x + half) >> 16;
CrG[i] = -Fix(0.71414) * x;
CbG[i] = -Fix(0.34414) * x + half;
}
}
public static YccTables For(int precision) => Cache[precision] ??= new YccTables(precision);
private static int Fix(double v) => (int)(v * 65536 + 0.5);
}
}
@@ -0,0 +1,255 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>
/// Entropy decoding of DCT scans into the components' coefficient arrays: sequential (baseline/extended) and the
/// four progressive scan kinds (DC first/refine, AC first/refine). Corrupt intervals are skipped by resynchronising
/// on the next RSTn marker; without restart markers the rest of the scan is abandoned with a warning.
/// </summary>
internal static class JpegScanDecoder
{
private enum Kind
{
Sequential,
DcFirst,
DcRefine,
AcFirst,
AcRefine,
}
public static int Decode(JpegParser parser, ReadOnlySpan<byte> data, int pos, JpegScan scan)
{
var frame = parser.Frame!;
var comps = scan.Components;
var kind = frame.Process != JpegProcess.Progressive ? Kind.Sequential
: scan.Ss == 0 ? (scan.Ah == 0 ? Kind.DcFirst : Kind.DcRefine)
: (scan.Ah == 0 ? Kind.AcFirst : Kind.AcRefine);
var single = comps.Length == 1;
var mcusX = single ? comps[0].WidthInBlocks : frame.McusX;
var mcusY = single ? comps[0].HeightInBlocks : frame.McusY;
var total = (long)mcusX * mcusY;
var interval = parser.RestartInterval;
var reader = new JpegBitReader(data, pos);
var state = new ScanState(scan);
var expectedRst = 0;
foreach (var c in comps) c.DcPred = 0;
long mcu = 0;
while (mcu < total)
{
var end = interval > 0 ? Math.Min(total, mcu + interval) : total;
try
{
for (; mcu < end; mcu++)
{
if (single)
{
var c = comps[0];
var bx = (int)(mcu % mcusX);
var by = (int)(mcu / mcusX);
DecodeBlock(ref reader, kind, c, (by * c.BlocksPerLine + bx) * 64, 0, ref state);
}
else
{
var mx = (int)(mcu % mcusX);
var my = (int)(mcu / mcusX);
for (var i = 0; i < comps.Length; i++)
{
var c = comps[i];
for (var v = 0; v < c.V; v++)
{
var row = (my * c.V + v) * c.BlocksPerLine + mx * c.H;
for (var h = 0; h < c.H; h++) DecodeBlock(ref reader, kind, c, (row + h) * 64, i, ref state);
}
}
}
if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data");
}
}
catch (JpegEntropyException ex)
{
parser.Warn(ex.Message);
if (interval == 0) break;
mcu = end;
}
if (mcu >= total || interval == 0) break;
if (!reader.NextRestart(ref expectedRst, out var lost))
{
parser.Warn("JPEG: restart marker missing; scan truncated");
break;
}
if (lost > 0)
{
// Intervals between the expected and the found marker were lost: leave their samples untouched.
parser.Warn($"JPEG: {lost} restart interval(s) lost");
mcu += (long)lost * interval;
}
state.EobRun = 0;
foreach (var c in comps) c.DcPred = 0;
}
return reader.Position;
}
private struct ScanState(JpegScan scan)
{
public readonly JpegScan Scan = scan;
public int EobRun;
}
private static void DecodeBlock(ref JpegBitReader r, Kind kind, JpegComponent c, int offset, int index, ref ScanState state)
{
var block = c.Coefficients.AsSpan(offset, 64);
var scan = state.Scan;
switch (kind)
{
case Kind.Sequential:
DecodeSequential(ref r, block, scan.DcTables[index]!, scan.AcTables[index]!, ref c.DcPred);
break;
case Kind.DcFirst:
{
var t = r.Decode(scan.DcTables[index]!);
if (t > 16) throw new JpegEntropyException("JPEG: bad DC magnitude");
c.DcPred += t == 0 ? 0 : r.Receive(t);
block[0] = (short)(c.DcPred * (1 << scan.Al));
break;
}
case Kind.DcRefine:
if (r.ReadBit() != 0) block[0] |= (short)(1 << scan.Al);
break;
case Kind.AcFirst:
DecodeAcFirst(ref r, block, scan.AcTables[index]!, scan.Ss, scan.Se, scan.Al, ref state.EobRun);
break;
default:
DecodeAcRefine(ref r, block, scan.AcTables[index]!, scan.Ss, scan.Se, scan.Al, ref state.EobRun);
break;
}
}
private static void DecodeSequential(ref JpegBitReader r, Span<short> block, JpegHuffmanTable dc, JpegHuffmanTable ac, ref int pred)
{
var t = r.Decode(dc);
if (t > 16) throw new JpegEntropyException("JPEG: bad DC magnitude");
pred += t == 0 ? 0 : r.Receive(t);
block[0] = (short)pred;
var order = JpegTables.NaturalOrder;
var fastAc = ac.FastAc;
var k = 1;
while (k < 64)
{
r.Ensure(16);
var fast = fastAc[r.Peek(JpegHuffmanTable.FastBits)];
if (fast != 0)
{
k += (fast >> 8) & 15;
r.Consume(fast & 0xFF);
if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range");
block[order[k++]] = (short)(fast >> 16);
continue;
}
var rs = r.Decode(ac);
int run = rs >> 4, s = rs & 15;
if (s == 0)
{
if (run != 15) break;
k += 16;
continue;
}
k += run;
if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range");
block[order[k++]] = (short)r.Receive(s);
}
}
private static void DecodeAcFirst(ref JpegBitReader r, Span<short> block, JpegHuffmanTable ac, int ss, int se, int al, ref int eobRun)
{
if (eobRun > 0)
{
eobRun--;
return;
}
var order = JpegTables.NaturalOrder;
for (var k = ss; k <= se;)
{
var rs = r.Decode(ac);
int run = rs >> 4, s = rs & 15;
if (s == 0)
{
if (run < 15)
{
eobRun = (1 << run) - 1;
if (run > 0) eobRun += r.ReadBits(run);
return;
}
k += 16;
continue;
}
k += run;
if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range");
block[order[k++]] = (short)(r.Receive(s) * (1 << al));
}
}
/// <summary>AC successive-approximation refinement (T.81 G.1.2.3), following libjpeg's decode_mcu_AC_refine.</summary>
private static void DecodeAcRefine(ref JpegBitReader r, Span<short> block, JpegHuffmanTable ac, int ss, int se, int al, ref int eobRun)
{
var order = JpegTables.NaturalOrder;
var p1 = (short)(1 << al);
var m1 = (short)(-1 << al);
var k = ss;
if (eobRun == 0)
{
for (; k <= se; k++)
{
var rs = r.Decode(ac);
int run = rs >> 4, s = rs & 15;
short value = 0;
if (s != 0)
{
if (s != 1) throw new JpegEntropyException("JPEG: bad refinement magnitude");
value = r.ReadBit() != 0 ? p1 : m1;
}
else if (run != 15)
{
eobRun = 1 << run;
if (run > 0) eobRun += r.ReadBits(run);
break;
}
// Skip `run` still-zero coefficients, refining the non-zero ones passed on the way.
for (; k <= se; k++)
{
ref var coef = ref block[order[k]];
if (coef != 0)
{
RefineBit(ref r, ref coef, p1, m1);
}
else
{
if (run == 0) break;
run--;
}
}
if (value != 0)
{
if (k > se) throw new JpegEntropyException("JPEG: refinement beyond spectral band");
block[order[k]] = value;
}
}
}
if (eobRun > 0)
{
for (; k <= se; k++)
{
ref var coef = ref block[order[k]];
if (coef != 0) RefineBit(ref r, ref coef, p1, m1);
}
eobRun--;
}
}
private static void RefineBit(ref JpegBitReader r, ref short coef, short p1, short m1)
{
if (r.ReadBit() == 0 || (coef & p1) != 0) return;
coef += coef >= 0 ? p1 : m1;
}
}
+96
View File
@@ -0,0 +1,96 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>Constants shared by the JPEG encoder and decoders (ITU T.81 Annex K).</summary>
internal static class JpegTables
{
public const byte Soi = 0xD8, Eoi = 0xD9, Sos = 0xDA, Dqt = 0xDB, Dri = 0xDD, Dht = 0xC4, Dac = 0xCC;
public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App14 = 0xEE;
/// <summary>Natural (row-major) index of the coefficient at each zig-zag position.</summary>
public static ReadOnlySpan<byte> NaturalOrder =>
[
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
];
/// <summary>Annex K.1 luminance quantisation table, natural order.</summary>
public static ReadOnlySpan<byte> LumaQuant =>
[
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99,
];
/// <summary>Annex K.1 chrominance quantisation table, natural order.</summary>
public static ReadOnlySpan<byte> ChromaQuant =>
[
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
];
public static ReadOnlySpan<byte> DcLumaBits => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
public static ReadOnlySpan<byte> DcLumaValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
public static ReadOnlySpan<byte> DcChromaBits => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
public static ReadOnlySpan<byte> DcChromaValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
public static ReadOnlySpan<byte> AcLumaBits => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
public static ReadOnlySpan<byte> AcLumaValues =>
[
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa,
];
public static ReadOnlySpan<byte> AcChromaBits => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
public static ReadOnlySpan<byte> AcChromaValues =>
[
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa,
];
/// <summary>Orthonormal 8-point DCT basis: <c>Basis[u * 8 + x] = c(u)/2 · cos((2x+1)uπ/16)</c>.</summary>
public static readonly float[] Basis = BuildBasis(8);
/// <summary>DCT basis of an n-point reduced IDCT evaluated with 8-point normalisation (DCT-domain scaling).</summary>
public static float[] BuildBasis(int n)
{
var b = new float[n * n];
for (var u = 0; u < n; u++)
{
var cu = u == 0 ? Math.Sqrt(0.5) : 1.0;
for (var x = 0; x < n; x++) b[u * n + x] = (float)(cu / 2 * Math.Cos((2 * x + 1) * u * Math.PI / (2 * n)));
}
return b;
}
}
+153
View File
@@ -0,0 +1,153 @@
namespace Titano.Core.Codecs.Jpeg;
/// <summary>JPEG coding process declared by the SOF marker.</summary>
public enum JpegProcess
{
/// <summary>SOF0: baseline sequential DCT, 8-bit, at most two Huffman tables per class.</summary>
Baseline,
/// <summary>SOF1: extended sequential DCT (8 or 12-bit).</summary>
ExtendedSequential,
/// <summary>SOF2: progressive DCT (spectral selection and successive approximation).</summary>
Progressive,
/// <summary>SOF3: lossless predictive coding (2–16 bit).</summary>
Lossless,
}
/// <summary>Colour space of the encoded components.</summary>
public enum JpegColorSpace
{
Gray,
YCbCr,
Rgb,
Cmyk,
Ycck,
/// <summary>No defined colour interpretation (e.g. two-component lossless raw tiles).</summary>
Other,
}
/// <summary>Overrides the colour interpretation of a 3- or 4-component stream (TIFF knows it out of band).</summary>
public enum JpegColorTransform
{
/// <summary>JFIF/Adobe markers and component ids decide (libjpeg rules).</summary>
Auto,
/// <summary>Components are stored as-is (RGB or CMYK).</summary>
None,
/// <summary>Components are YCbCr (or YCCK for four components).</summary>
YCbCr,
}
/// <summary>Frame facts from the headers, available without decoding pixels.</summary>
/// <param name="Width">Full image width in pixels.</param>
/// <param name="Height">Full image height in pixels.</param>
/// <param name="Components">Number of encoded components (1–4).</param>
/// <param name="Precision">Sample precision in bits (8 or 12 for DCT, 2–16 for lossless).</param>
/// <param name="Process">Coding process.</param>
/// <param name="ColorSpace">Colour space the decoder will assume.</param>
/// <param name="Sampling">Horizontal and vertical sampling factors per component.</param>
/// <param name="RestartInterval">Restart interval in MCUs declared before the first scan (0 = none).</param>
public sealed record JpegInfo(
int Width,
int Height,
int Components,
int Precision,
JpegProcess Process,
JpegColorSpace ColorSpace,
IReadOnlyList<(int H, int V)> Sampling,
int RestartInterval)
{
/// <summary>Chroma subsampling in J:a:b notation for three-component images ("4:2:0"), otherwise a factor list.</summary>
public string SamplingNotation
{
get
{
if (Sampling.Count == 3 && Sampling[1] == Sampling[2] && Sampling[1] == (1, 1))
{
return Sampling[0] switch
{
(1, 1) => "4:4:4",
(2, 1) => "4:2:2",
(2, 2) => "4:2:0",
(1, 2) => "4:4:0",
(4, 1) => "4:1:1",
(4, 2) => "4:1:0",
_ => Factors(),
};
}
return Factors();
}
}
private string Factors() => string.Join(",", Sampling.Select(s => $"{s.H}x{s.V}"));
}
/// <summary>Options for <see cref="JpegDecoder"/>.</summary>
public sealed record JpegDecodeOptions
{
/// <summary>Default options: full size, fancy upsampling, automatic colour transform.</summary>
public static JpegDecodeOptions Default { get; } = new();
/// <summary>When &gt; 0, decode with the smallest DCT-domain reduction (1/2, 1/4, 1/8) whose long edge is still
/// ≥ this value. 0 decodes at full size. Ignored for lossless streams.</summary>
public int MaxLongEdge { get; init; }
/// <summary>Triangle-filter chroma upsampling (libjpeg "fancy"); false replicates chroma samples.</summary>
public bool FancyUpsampling { get; init; } = true;
/// <summary>Colour interpretation override (TIFF photometric).</summary>
public JpegColorTransform ColorTransform { get; init; } = JpegColorTransform.Auto;
/// <summary>Abbreviated table-specification stream (TIFF JPEGTables) parsed before the image stream.</summary>
public byte[]? Tables { get; init; }
/// <summary>Upper bound on width × height; larger frames are rejected before any allocation.</summary>
public long MaxPixels { get; init; } = 1L << 28;
/// <summary>Worker limit for the IDCT and colour stages (-1 = all cores, 1 = single-threaded).</summary>
public int MaxDegreeOfParallelism { get; init; } = -1;
}
/// <summary>Decoded JPEG pixels, interleaved, top-down, Exif orientation not applied.</summary>
public sealed class JpegImage
{
internal JpegImage(JpegInfo info, int width, int height, int components, int bitDepth, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList<string> warnings)
{
Info = info;
Width = width;
Height = height;
Components = components;
BitDepth = bitDepth;
Pixels8 = pixels8;
Pixels16 = pixels16;
Warnings = warnings;
}
/// <summary>Header facts of the source stream (full-size dimensions).</summary>
public JpegInfo Info { get; }
/// <summary>Output width (smaller than <see cref="JpegInfo.Width"/> when DCT scaling was used).</summary>
public int Width { get; }
public int Height { get; }
/// <summary>Output channels: 1 (gray) or 3 (RGB; CMYK/YCCK are converted).</summary>
public int Components { get; }
/// <summary>Significant bits per sample: 8 → <see cref="Pixels8"/>; more → <see cref="Pixels16"/> with values 0..2^BitDepth−1.</summary>
public int BitDepth { get; }
public byte[]? Pixels8 { get; }
public ushort[]? Pixels16 { get; }
/// <summary>Recoverable problems (corrupt entropy data, missing restart markers, truncation).</summary>
public IReadOnlyList<string> Warnings { get; }
}
/// <summary>Raw samples of a lossless (SOF3) stream as encoded: interleaved, <see cref="Width"/> as in the frame header.</summary>
public readonly record struct JpegLosslessImage(ushort[] Samples, int Width, int Height, int Components, int Precision);
+359
View File
@@ -0,0 +1,359 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Png;
/// <summary>IHDR facts of a PNG stream.</summary>
public sealed record PngInfo(int Width, int Height, int BitDepth, PngColorType ColorType, bool Interlaced);
/// <summary>Decoded PNG pixels: interleaved, top-down, palette and tRNS expanded.</summary>
public sealed class PngImage
{
internal PngImage(PngInfo info, int channels, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList<string> warnings)
{
Info = info;
Channels = channels;
Pixels8 = pixels8;
Pixels16 = pixels16;
Warnings = warnings;
}
public PngInfo Info { get; }
public int Width => Info.Width;
public int Height => Info.Height;
/// <summary>1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA (palette → RGB/RGBA; tRNS adds alpha).</summary>
public int Channels { get; }
/// <summary>8 (<see cref="Pixels8"/>; 1/2/4-bit gray is scaled to 0..255) or 16 (<see cref="Pixels16"/>).</summary>
public int BitDepth => Pixels16 is null ? 8 : 16;
public byte[]? Pixels8 { get; }
public ushort[]? Pixels16 { get; }
/// <summary>Recoverable problems (CRC mismatches, truncated or corrupt image data, unknown critical chunks).</summary>
public IReadOnlyList<string> Warnings { get; }
}
/// <summary>
/// PNG decoder: every colour type and bit depth (1/2/4/8/16), PLTE + tRNS, Adam7, all five filters, zlib through
/// <see cref="ZLibStream"/>. CRC mismatches are tolerated with a warning; damaged image data yields the rows decoded so
/// far plus a warning. Ancillary colour chunks (gAMA, iCCP, cHRM) are ignored: samples are taken as sRGB.
/// </summary>
public static class PngDecoder
{
private static ReadOnlySpan<byte> Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
private static readonly (int X, int Y, int Dx, int Dy)[] Adam7 =
[(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)];
public static PngInfo ReadInfo(ReadOnlySpan<byte> data)
{
if (data.Length < 33 || !data.StartsWith(Signature) || !data.Slice(12, 4).SequenceEqual("IHDR"u8))
throw new InvalidDataException("PNG: missing signature or IHDR");
return ParseHeader(data.Slice(16, 13));
}
/// <param name="maxPixels">Upper bound on width × height, checked before allocation.</param>
public static PngImage Decode(ReadOnlySpan<byte> data, long maxPixels = 1L << 28)
{
var info = ReadInfo(data);
if ((long)info.Width * info.Height > maxPixels) throw new InvalidDataException($"PNG: {info.Width}x{info.Height} exceeds the pixel limit");
var warnings = new List<string>();
byte[]? palette = null;
byte[]? trns = null;
using var idat = new MemoryStream();
var pos = 8;
var ended = false;
while (pos + 8 <= data.Length)
{
var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]);
var type = data.Slice(pos + 4, 4);
if (length > int.MaxValue || pos + 12 + (long)length > data.Length)
{
warnings.Add("PNG: truncated chunk");
break;
}
var body = data.Slice(pos + 8, (int)length);
var crc = BinaryPrimitives.ReadUInt32BigEndian(data[(pos + 8 + (int)length)..]);
if (Crc32.Compute(data.Slice(pos + 4, 4 + (int)length)) != crc) warnings.Add($"PNG: CRC mismatch in {Name(type)}");
pos += 12 + (int)length;
if (type.SequenceEqual("IDAT"u8))
{
idat.Write(body);
}
else if (type.SequenceEqual("PLTE"u8))
{
if (body.Length % 3 != 0 || body.Length > 768 || body.Length == 0) throw new InvalidDataException("PNG: bad PLTE");
palette = body.ToArray();
}
else if (type.SequenceEqual("tRNS"u8))
{
trns = body.ToArray();
}
else if (type.SequenceEqual("IEND"u8))
{
ended = true;
break;
}
else if (!type.SequenceEqual("IHDR"u8) && (type[0] & 0x20) == 0)
{
warnings.Add($"PNG: unknown critical chunk {Name(type)} ignored");
}
}
if (!ended) warnings.Add("PNG: missing IEND");
if (idat.Length == 0) throw new InvalidDataException("PNG: no image data");
if (info.ColorType == PngColorType.Palette && palette is null) throw new InvalidDataException("PNG: palette image without PLTE");
var layout = Layout.For(info, palette, trns);
idat.Position = 0;
using var z = new ZLibStream(idat, CompressionMode.Decompress);
return layout.Sixteen ? Decode16(info, layout, z, warnings) : Decode8(info, layout, z, warnings);
}
/// <summary>Decodes into a linear-light buffer (samples are sRGB-encoded; alpha stays linear).</summary>
/// <param name="expandGray">Return gray as three identical channels.</param>
/// <param name="keepAlpha">Keep alpha as a fourth channel (gray is then expanded).</param>
public static ImageBuffer DecodeToLinear(ReadOnlySpan<byte> data, bool expandGray = false, bool keepAlpha = false)
{
var image = Decode(data);
var gray = image.Channels <= 2;
var hasAlpha = image.Channels is 2 or 4;
var output = keepAlpha && hasAlpha ? 4 : gray && !expandGray ? 1 : 3;
return image.Pixels8 is { } p8
? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Channels, outputChannels: output)
: PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Channels, outputChannels: output);
}
private static string Name(ReadOnlySpan<byte> type) => string.Create(4, type.ToArray(), (s, t) =>
{
for (var i = 0; i < 4; i++) s[i] = t[i] is >= 32 and < 127 ? (char)t[i] : '?';
});
private static PngInfo ParseHeader(ReadOnlySpan<byte> h)
{
var width = BinaryPrimitives.ReadUInt32BigEndian(h);
var height = BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
int depth = h[8], type = h[9];
if (width is 0 or > int.MaxValue || height is 0 or > int.MaxValue) throw new InvalidDataException("PNG: bad dimensions");
var valid = type switch
{
0 => depth is 1 or 2 or 4 or 8 or 16,
3 => depth is 1 or 2 or 4 or 8,
2 or 4 or 6 => depth is 8 or 16,
_ => false,
};
if (!valid) throw new InvalidDataException($"PNG: invalid colour type {type} / bit depth {depth}");
if (h[10] != 0 || h[11] != 0 || h[12] > 1) throw new InvalidDataException("PNG: unsupported compression, filter or interlace method");
return new PngInfo((int)width, (int)height, depth, (PngColorType)type, h[12] == 1);
}
/// <summary>Sample geometry of the stored scanlines and of the expanded output.</summary>
private sealed class Layout
{
public int SourceChannels, BitsPerPixel, BytesPerPixel, OutChannels;
public bool Sixteen;
public byte[]? Palette;
public byte[]? PaletteAlpha;
/// <summary>tRNS colour key in source sample units (gray: 1 value, RGB: 3), or null.</summary>
public int[]? Key;
public static Layout For(PngInfo info, byte[]? palette, byte[]? trns)
{
var l = new Layout
{
SourceChannels = info.ColorType switch
{
PngColorType.Gray or PngColorType.Palette => 1,
PngColorType.GrayAlpha => 2,
PngColorType.Rgb => 3,
_ => 4,
},
Sixteen = info.BitDepth == 16,
};
l.BitsPerPixel = l.SourceChannels * info.BitDepth;
l.BytesPerPixel = Math.Max(1, l.BitsPerPixel / 8);
l.OutChannels = l.SourceChannels;
switch (info.ColorType)
{
case PngColorType.Palette:
l.Palette = palette;
l.OutChannels = 3;
if (trns is { Length: > 0 })
{
l.PaletteAlpha = new byte[256];
Array.Fill(l.PaletteAlpha, (byte)255);
trns.AsSpan(0, Math.Min(trns.Length, 256)).CopyTo(l.PaletteAlpha);
l.OutChannels = 4;
}
break;
case PngColorType.Gray when trns is { Length: >= 2 }:
l.Key = [trns[0] << 8 | trns[1]];
l.OutChannels = 2;
break;
case PngColorType.Rgb when trns is { Length: >= 6 }:
l.Key = [trns[0] << 8 | trns[1], trns[2] << 8 | trns[3], trns[4] << 8 | trns[5]];
l.OutChannels = 4;
break;
}
return l;
}
}
private static PngImage Decode8(PngInfo info, Layout l, Stream z, List<string> warnings)
{
var pixels = new byte[checked((long)info.Width * info.Height * l.OutChannels)];
var row = new byte[info.Width * l.OutChannels];
Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
{
Expand8(raw, info.BitDepth, count, l, row);
for (int i = 0, x = x0; i < count; i++, x += dx)
{
row.AsSpan(i * l.OutChannels, l.OutChannels).CopyTo(pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels)));
}
});
return new PngImage(info, l.OutChannels, pixels, null, warnings);
}
private static PngImage Decode16(PngInfo info, Layout l, Stream z, List<string> warnings)
{
var pixels = new ushort[checked((long)info.Width * info.Height * l.OutChannels)];
Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
{
for (int i = 0, x = x0; i < count; i++, x += dx)
{
var dst = pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels), l.OutChannels);
var transparent = l.Key is not null;
for (var c = 0; c < l.SourceChannels; c++)
{
dst[c] = BinaryPrimitives.ReadUInt16BigEndian(raw[((i * l.SourceChannels + c) * 2)..]);
if (l.Key is not null && dst[c] != l.Key[c]) transparent = false;
}
if (l.Key is not null) dst[l.SourceChannels] = transparent ? (ushort)0 : ushort.MaxValue;
}
});
return new PngImage(info, l.OutChannels, null, pixels, warnings);
}
private delegate void RowHandler(ReadOnlySpan<byte> raw, int y, int x0, int dx, int count);
/// <summary>Streams every (pass,) row out of zlib, unfilters it and hands the raw samples to <paramref name="handle"/>.</summary>
private static void Inflate(PngInfo info, Layout l, Stream z, List<string> warnings, RowHandler handle)
{
var passes = info.Interlaced ? Adam7 : [(0, 0, 1, 1)];
var maxRow = (int)(((long)info.Width * l.BitsPerPixel + 7) / 8);
var line = new byte[maxRow + 1];
var prior = new byte[maxRow];
try
{
foreach (var (px, py, dx, dy) in passes)
{
if (px >= info.Width || py >= info.Height) continue;
var count = (info.Width - px + dx - 1) / dx;
var rowBytes = (int)(((long)count * l.BitsPerPixel + 7) / 8);
Array.Clear(prior);
for (var y = py; y < info.Height; y += dy)
{
var buffer = line.AsSpan(0, rowBytes + 1);
if (z.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) < buffer.Length)
{
warnings.Add("PNG: image data truncated");
return;
}
if (buffer[0] > 4)
{
warnings.Add($"PNG: invalid filter type {buffer[0]}");
return;
}
var row = buffer[1..];
Unfilter(buffer[0], row, prior.AsSpan(0, rowBytes), l.BytesPerPixel);
handle(row, y, px, dx, count);
row.CopyTo(prior);
}
}
}
catch (InvalidDataException ex)
{
warnings.Add("PNG: corrupt image data: " + ex.Message);
}
}
private static void Unfilter(int filter, Span<byte> row, ReadOnlySpan<byte> prior, int bpp)
{
switch (filter)
{
case 1:
for (var i = bpp; i < row.Length; i++) row[i] += row[i - bpp];
break;
case 2:
for (var i = 0; i < row.Length; i++) row[i] += prior[i];
break;
case 3:
for (var i = 0; i < bpp && i < row.Length; i++) row[i] += (byte)(prior[i] >> 1);
for (var i = bpp; i < row.Length; i++) row[i] += (byte)((row[i - bpp] + prior[i]) >> 1);
break;
case 4:
for (var i = 0; i < bpp && i < row.Length; i++) row[i] += prior[i];
for (var i = bpp; i < row.Length; i++) row[i] += (byte)PngEncoder.Paeth(row[i - bpp], prior[i], prior[i - bpp]);
break;
}
}
/// <summary>Expands one row of ≤ 8-bit samples (sub-byte gray, palette, tRNS key) to 8-bit output channels.</summary>
private static void Expand8(ReadOnlySpan<byte> raw, int depth, int count, Layout l, Span<byte> dst)
{
var oc = l.OutChannels;
if (depth == 8 && l.Palette is null && l.Key is null)
{
raw[..(count * oc)].CopyTo(dst);
return;
}
if (depth == 8 && l.Key is not null)
{
var sc = l.SourceChannels;
for (var i = 0; i < count; i++)
{
var opaque = false;
for (var c = 0; c < sc; c++)
{
var v = raw[i * sc + c];
dst[i * oc + c] = v;
if (v != l.Key[c]) opaque = true;
}
dst[i * oc + sc] = opaque ? (byte)255 : (byte)0;
}
return;
}
// Sub-byte or palette: one sample per pixel, MSB first.
var mask = (1 << depth) - 1;
var scale = l.Palette is null ? 255 / mask : 1;
for (var i = 0; i < count; i++)
{
var bit = i * depth;
var v = (raw[bit >> 3] >> (8 - depth - (bit & 7))) & mask;
if (l.Palette is { } pal)
{
var o = dst.Slice(i * oc, oc);
if (3 * v + 2 < pal.Length)
{
o[0] = pal[3 * v];
o[1] = pal[3 * v + 1];
o[2] = pal[3 * v + 2];
}
else
{
o[..3].Clear(); // out-of-range index: black, as libpng
}
if (oc == 4) o[3] = l.PaletteAlpha![v];
}
else
{
dst[i * oc] = (byte)(v * scale);
if (l.Key is not null) dst[i * oc + 1] = v == l.Key[0] ? (byte)0 : (byte)255;
}
}
}
}
+34 -1
View File
@@ -1,14 +1,16 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Png;
/// <summary>PNG colour types written by <see cref="PngEncoder"/>.</summary>
/// <summary>PNG colour types (<see cref="Palette"/> is decoded but never written by <see cref="PngEncoder"/>).</summary>
public enum PngColorType : byte
{
Gray = 0,
Rgb = 2,
Palette = 3,
GrayAlpha = 4,
Rgba = 6,
}
@@ -29,6 +31,7 @@ public static class PngEncoder
public static void Encode(Stream output, ReadOnlySpan<byte> pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
{
if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
if (colorType == PngColorType.Palette) throw new ArgumentException("Palette images are not written", nameof(colorType));
var channels = colorType switch
{
PngColorType.Gray => 1,
@@ -60,6 +63,36 @@ public static class PngEncoder
WriteChunk(output, "IEND", []);
}
/// <summary>Encodes a linear-light buffer as sRGB-encoded PNG (1 channel → gray, 3 → RGB, 4 → RGBA with linear
/// alpha) and tags it with an sRGB chunk.</summary>
/// <param name="bitDepth">8 or 16 bits per sample.</param>
public static byte[] Encode(ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize)
{
using var ms = new MemoryStream();
Encode(ms, image, bitDepth, level);
return ms.ToArray();
}
public static void Encode(Stream output, ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
{
if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
var channels = image.Channels;
var colorType = channels switch { 1 => PngColorType.Gray, 3 => PngColorType.Rgb, _ => PngColorType.Rgba };
byte[] pixels;
if (bitDepth == 8)
{
pixels = PixelConvert.ToInterleaved8(image, channels);
}
else
{
var words = PixelConvert.ToInterleaved16(image, channels);
pixels = new byte[words.Length * 2];
for (var i = 0; i < words.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(pixels.AsSpan(2 * i), words[i]);
}
IEnumerable<(string Type, byte[] Data)> chunks = [("sRGB", [0]), .. extraChunks ?? []];
Encode(output, pixels, image.Width, image.Height, colorType, bitDepth, level, chunks);
}
/// <summary>Filters every row (adaptive, minimum sum of absolute differences) and deflates the result.</summary>
public static byte[] Compress(ReadOnlySpan<byte> pixels, int height, int stride, int bpp, CompressionLevel level)
{
@@ -0,0 +1,121 @@
using System.IO.Compression;
namespace Titano.Core.Codecs.Tiff;
/// <summary>
/// Strip/tile decompressors. Each fills exactly <c>output.Length</c> bytes when the data allows and returns the number
/// of bytes produced; damaged data ends early instead of throwing out of range.
/// </summary>
internal static class TiffDecompressors
{
/// <summary>TIFF LZW (MSB-first codes, "early change"). Old-style streams (pre-6.0 libtiff, LSB-first codes,
/// no early change) are recognised by their first byte as libtiff does.</summary>
public static int Lzw(ReadOnlySpan<byte> input, Span<byte> output)
{
const int clear = 256, eoi = 257, maxCodes = 4096;
var oldStyle = input.Length >= 2 && input[0] == 0 && (input[1] & 1) != 0;
Span<ushort> prefix = stackalloc ushort[maxCodes];
Span<byte> suffix = stackalloc byte[maxCodes];
Span<byte> first = stackalloc byte[maxCodes];
Span<ushort> length = stackalloc ushort[maxCodes];
for (var i = 0; i < 256; i++)
{
suffix[i] = first[i] = (byte)i;
length[i] = 1;
}
int next = 258, width = 9, old = -1, written = 0, inPos = 0, bits = 0;
uint acc = 0;
var early = oldStyle ? 0 : 1;
while (written < output.Length)
{
while (bits < width && inPos < input.Length)
{
if (oldStyle) acc |= (uint)input[inPos++] << bits;
else acc = acc << 8 | input[inPos++];
bits += 8;
}
if (bits < width) break;
int code;
if (oldStyle)
{
code = (int)(acc & ((1u << width) - 1));
acc >>= width;
}
else
{
code = (int)(acc >> (bits - width)) & ((1 << width) - 1);
}
bits -= width;
if (code == eoi) break;
if (code == clear)
{
next = 258;
width = 9;
old = -1;
continue;
}
if (old < 0)
{
if (code > 255) break; // the first code after a clear must be a literal
}
else
{
if (code > next || next >= maxCodes && code == next) break; // corrupt: code beyond the table
if (next < maxCodes)
{
// New entry: old string + first byte of the current string (KwKwK when code == next).
prefix[next] = (ushort)old;
suffix[next] = code < next ? first[code] : first[old];
first[next] = first[old];
length[next] = (ushort)Math.Min(ushort.MaxValue, length[old] + 1);
next++;
}
}
// Strings are prefix chains: write back to front, clipped to the output.
var len = length[code];
var end = Math.Min(written + len, output.Length);
var c = code;
for (var p = written + len - 1; p >= written; p--)
{
if (p < end) output[p] = suffix[c];
c = prefix[c];
}
written = end;
old = code;
if (next + early >= 1 << width && width < 12) width++;
}
return written;
}
/// <summary>Macintosh PackBits run-length decoding.</summary>
public static int PackBits(ReadOnlySpan<byte> input, Span<byte> output)
{
int i = 0, o = 0;
while (i < input.Length && o < output.Length)
{
var n = (sbyte)input[i++];
if (n >= 0)
{
var count = Math.Min(n + 1, Math.Min(input.Length - i, output.Length - o));
input.Slice(i, count).CopyTo(output[o..]);
i += n + 1;
o += count;
}
else if (n != -128)
{
if (i >= input.Length) break;
var count = Math.Min(1 - n, output.Length - o);
output.Slice(o, count).Fill(input[i++]);
o += count;
}
}
return o;
}
/// <summary>zlib (Adobe Deflate, TIFF compression 8/32946).</summary>
public static int Deflate(byte[] input, Span<byte> output)
{
using var z = new ZLibStream(new MemoryStream(input, writable: false), CompressionMode.Decompress);
return z.ReadAtLeast(output, output.Length, throwOnEndOfStream: false);
}
}
@@ -0,0 +1,189 @@
using System.Buffers.Binary;
using System.Text;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Codecs.Tiff;
/// <summary>
/// A little-endian IFD under construction for <see cref="TiffWriter"/> and the DNG writer: entries kept sorted by
/// tag, values ≤ 4 bytes inline, larger ones word-aligned after the entry table, child IFDs (Exif, GPS, Interop)
/// laid out after their parent.
/// </summary>
internal sealed class TiffDirectory
{
private readonly SortedDictionary<ushort, (TiffType Type, int Count, byte[] Value)> _entries = [];
private readonly SortedDictionary<ushort, TiffDirectory> _children = [];
private long _offset = -1;
public bool Has(ushort tag) => _entries.ContainsKey(tag) || _children.ContainsKey(tag);
/// <summary>Adds an entry whose value bytes are already little-endian.</summary>
public void Add(ushort tag, TiffType type, int count, byte[] value) => _entries[tag] = (type, count, value);
public void Short(ushort tag, params ReadOnlySpan<ushort> values)
{
var b = new byte[values.Length * 2];
for (var i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(b.AsSpan(2 * i), values[i]);
Add(tag, TiffType.Short, values.Length, b);
}
public void Long(ushort tag, params ReadOnlySpan<uint> values)
{
var b = new byte[values.Length * 4];
for (var i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4 * i), values[i]);
Add(tag, TiffType.Long, values.Length, b);
}
public void Rational(ushort tag, params ReadOnlySpan<(uint Numerator, uint Denominator)> values)
{
var b = new byte[values.Length * 8];
for (var i = 0; i < values.Length; i++)
{
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8 * i), values[i].Numerator);
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8 * i + 4), values[i].Denominator);
}
Add(tag, TiffType.Rational, values.Length, b);
}
public void SRational(ushort tag, params ReadOnlySpan<(int Numerator, int Denominator)> values)
{
var b = new byte[values.Length * 8];
for (var i = 0; i < values.Length; i++)
{
BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(8 * i), values[i].Numerator);
BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(8 * i + 4), values[i].Denominator);
}
Add(tag, TiffType.SRational, values.Length, b);
}
public void Ascii(ushort tag, string value)
{
var b = Encoding.UTF8.GetBytes(value + "\0");
Add(tag, TiffType.Ascii, b.Length, b);
}
public void Bytes(ushort tag, params ReadOnlySpan<byte> values) => Add(tag, TiffType.Byte, values.Length, values.ToArray());
/// <summary>Links a sub-IFD through a LONG pointer entry (resolved during <see cref="Layout"/>).</summary>
public void Child(ushort tag, TiffDirectory child) => _children[tag] = child;
private int OwnSize
{
get
{
var size = 2 + 12 * (_entries.Count + _children.Count) + 4;
foreach (var (_, (_, _, value)) in _entries)
{
if (value.Length > 4) size += (value.Length + 1) & ~1;
}
return size;
}
}
/// <summary>Assigns file offsets to this directory and its children (depth first); returns the end offset.</summary>
public long Layout(long offset)
{
_offset = (offset + 1) & ~1L;
var end = _offset + OwnSize;
foreach (var child in _children.Values) end = child.Layout(end);
if (end > uint.MaxValue) throw new InvalidOperationException("TIFF exceeds 4 GB");
return end;
}
/// <summary>Writes this directory and its children at the offsets chosen by <see cref="Layout"/>.</summary>
/// <param name="output">Positioned at or before this directory's offset.</param>
public void Write(Stream output)
{
if (_offset < 0) throw new InvalidOperationException("Layout must run before Write");
while (output.Position < _offset) output.WriteByte(0);
var buffer = new byte[OwnSize];
var count = _entries.Count + _children.Count;
BinaryPrimitives.WriteUInt16LittleEndian(buffer, (ushort)count);
var valueAt = 2 + 12 * count + 4;
var e = 2;
var all = _entries.Select(kv => (kv.Key, kv.Value.Type, kv.Value.Count, kv.Value.Value, Child: (TiffDirectory?)null))
.Concat(_children.Select(kv => (kv.Key, TiffType.Long, 1, Array.Empty<byte>(), Child: (TiffDirectory?)kv.Value)))
.OrderBy(x => x.Key);
foreach (var (tag, type, n, value, child) in all)
{
var entry = buffer.AsSpan(e, 12);
BinaryPrimitives.WriteUInt16LittleEndian(entry, tag);
BinaryPrimitives.WriteUInt16LittleEndian(entry[2..], (ushort)type);
BinaryPrimitives.WriteUInt32LittleEndian(entry[4..], (uint)n);
if (child is not null)
{
BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)child._offset);
}
else if (value.Length <= 4)
{
value.CopyTo(entry[8..]);
}
else
{
BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)(_offset + valueAt));
value.CopyTo(buffer.AsSpan(valueAt));
valueAt += (value.Length + 1) & ~1;
}
e += 12;
}
output.Write(buffer);
foreach (var child in _children.Values) child.Write(output);
}
/// <summary>
/// Copies capture metadata from a TIFF-structured Exif block (a JPEG APP1 payload, with or without the
/// "Exif\0\0" prefix): IFD0 descriptive tags plus the Exif (with Interop) and GPS sub-IFDs, converted to
/// little-endian. Maker notes are copied as opaque bytes (offsets inside them are not rebased).
/// </summary>
public void AttachExif(byte[] exif)
{
var start = exif.AsSpan().StartsWith("Exif\0\0"u8) ? 6 : 0;
using var stream = new MemoryStream(exif, start, exif.Length - start, writable: false);
var reader = TiffReader.Open(stream) ?? throw new ArgumentException("Exif block is not TIFF-structured", nameof(exif));
var chain = reader.ReadChain();
if (chain.Count == 0) throw new ArgumentException("Exif block has no IFD", nameof(exif));
var ifd0 = chain[0];
foreach (var tag in (ReadOnlySpan<ushort>)[TiffTags.ImageDescription, TiffTags.Make, TiffTags.Model, TiffTags.DateTime, TiffTags.Artist, TiffTags.Copyright])
{
if (!Has(tag) && ifd0.Entries.TryGetValue(tag, out var entry)) CopyEntry(reader, entry);
}
var visited = new HashSet<long> { ifd0.Position };
foreach (var pointer in (ReadOnlySpan<ushort>)[TiffTags.ExifIfd, TiffTags.GpsIfd])
{
if (reader.GetUInt(ifd0, pointer) is { } offset && reader.ReadIfd(offset, visited) is { } sub) Child(pointer, CopyDirectory(reader, sub, visited, 0));
}
}
private static TiffDirectory CopyDirectory(TiffReader reader, Ifd source, HashSet<long> visited, int depth)
{
var copy = new TiffDirectory();
foreach (var entry in source.Entries.Values)
{
if (entry.Tag == TiffTags.InteropIfd)
{
if (depth < 2 && reader.GetUInts(entry) is [var offset, ..] && reader.ReadIfd(offset, visited) is { } interop)
copy.Child(entry.Tag, CopyDirectory(reader, interop, visited, depth + 1));
continue;
}
copy.CopyEntry(reader, entry);
}
return copy;
}
private void CopyEntry(TiffReader reader, IfdEntry entry)
{
if (reader.ReadBytes(entry) is not { } value) return;
if (!reader.LittleEndian)
{
var size = entry.Type switch
{
TiffType.Short or TiffType.SShort => 2,
TiffType.Long or TiffType.SLong or TiffType.Float or TiffType.Ifd or TiffType.Rational or TiffType.SRational => 4,
TiffType.Double => 8,
_ => 1,
};
for (var i = 0; size > 1 && i + size <= value.Length; i += size) value.AsSpan(i, size).Reverse();
}
Add(entry.Tag, entry.Type, (int)entry.Count, value);
}
}
@@ -0,0 +1,445 @@
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Codecs.Tiff;
/// <summary>TIFF SampleFormat values handled by <see cref="TiffImageReader"/>.</summary>
public enum TiffSampleFormat
{
UnsignedInteger = 1,
Float = 3,
}
/// <summary>Decoded samples of one IFD: chunky (interleaved), top-down, cropped to the image size.</summary>
public sealed class TiffRaster
{
internal TiffRaster(int width, int height, int samplesPerPixel, int bitsPerSample, TiffSampleFormat format, int photometric, ushort[]? samples, float[]? floats, IReadOnlyList<string> warnings)
{
Width = width;
Height = height;
SamplesPerPixel = samplesPerPixel;
BitsPerSample = bitsPerSample;
SampleFormat = format;
Photometric = photometric;
Samples = samples;
FloatSamples = floats;
Warnings = warnings;
}
public int Width { get; }
public int Height { get; }
public int SamplesPerPixel { get; }
/// <summary>Significant bits per sample (integer samples are 0..2^bits−1; JPEG tiles report their precision).</summary>
public int BitsPerSample { get; }
public TiffSampleFormat SampleFormat { get; }
/// <summary>PhotometricInterpretation of the samples as returned (JPEG-coded YCbCr is delivered as RGB = 2).</summary>
public int Photometric { get; }
/// <summary>Integer samples (<see cref="TiffSampleFormat.UnsignedInteger"/>).</summary>
public ushort[]? Samples { get; }
/// <summary>Floating-point samples (16/32-bit float TIFF and DNG).</summary>
public float[]? FloatSamples { get; }
/// <summary>Recoverable problems (missing or truncated strips/tiles, JPEG warnings).</summary>
public IReadOnlyList<string> Warnings { get; }
}
/// <summary>Options for <see cref="TiffImageReader"/>.</summary>
public sealed record TiffDecodeOptions
{
public static TiffDecodeOptions Default { get; } = new();
/// <summary>Integer samples are linear light (otherwise sRGB-encoded is assumed; LinearRaw is always linear).</summary>
public bool AssumeLinear { get; init; }
/// <summary>Upper bound on width × height × samples per pixel, checked before allocation.</summary>
public long MaxSamples { get; init; } = 1L << 29;
/// <summary>Worker limit for strip/tile decoding (-1 = all cores).</summary>
public int MaxDegreeOfParallelism { get; init; } = -1;
}
/// <summary>
/// TIFF/DNG pixel data on top of <see cref="TiffReader"/>: strips and tiles, chunky and planar, compression none / LZW
/// (old-style bit order tolerated) / Deflate / PackBits / JPEG (with JPEGTables; YCbCr or RGB; lossless SOF3 for DNG,
/// including tiles whose JPEG frame is laid out as e.g. 2 components × width/2), predictors 2 and 3 (and the DNG ×2/×4
/// variants), 1–16-bit integer and 16/32-bit float samples. Strips and tiles decode in parallel.
/// </summary>
public static class TiffImageReader
{
private const int CompressionNone = 1, CompressionLzw = 5, CompressionJpeg = 7, CompressionDeflate = 8;
private const int CompressionAdobeDeflate = 32946, CompressionPackBits = 32773, CompressionLossyJpeg = 34892;
private const int PhotometricMinIsWhite = 0, PhotometricRgb = 2, PhotometricPalette = 3, PhotometricYCbCr = 6;
private const int PhotometricCfa = 32803, PhotometricLinearRaw = 34892;
private const int MaxChunks = 1 << 24;
private const long MaxChunkBytes = int.MaxValue / 2;
/// <summary>Decodes the first full-resolution image of a TIFF (or a DNG whose main image is not CFA).</summary>
public static ImageBuffer Decode(Stream stream, TiffDecodeOptions? options = null)
{
var reader = TiffReader.Open(stream) ?? throw new InvalidDataException("TIFF: missing header");
var chain = reader.ReadChain();
if (chain.Count == 0) throw new InvalidDataException("TIFF: no image directory");
var ifd = chain.FirstOrDefault(i => ((reader.GetUInt(i, TiffTags.NewSubfileType) ?? 0) & 1) == 0) ?? chain[0];
var o = options ?? TiffDecodeOptions.Default;
return ToImageBuffer(ReadRaster(reader, ifd, o), o);
}
public static ImageBuffer Decode(byte[] data, TiffDecodeOptions? options = null) => Decode(new MemoryStream(data, writable: false), options);
/// <summary>Converts a gray/RGB raster to linear light (min-is-white inverted; extra samples dropped).</summary>
public static ImageBuffer ToImageBuffer(TiffRaster raster, TiffDecodeOptions? options = null)
{
var o = options ?? TiffDecodeOptions.Default;
if (raster.Photometric is PhotometricCfa or PhotometricPalette)
throw new InvalidDataException($"TIFF: photometric {raster.Photometric} needs colour reconstruction (CFA/palette) not done here");
int w = raster.Width, h = raster.Height, spp = raster.SamplesPerPixel;
var colour = spp >= 3 && raster.Photometric is PhotometricRgb or PhotometricLinearRaw;
var channels = colour ? 3 : 1;
if (raster.FloatSamples is { } floats)
{
var image = new ImageBuffer(w, h, channels, clear: false);
for (var c = 0; c < channels; c++)
{
var plane = image.Plane(c);
for (var i = 0; i < plane.Length; i++) plane[i] = floats[i * spp + c];
}
return image;
}
var samples = raster.Samples!;
var max = (1 << raster.BitsPerSample) - 1;
var packedChannels = colour ? Math.Min(spp, 4) : Math.Min(spp, 2);
if (raster.Photometric == PhotometricMinIsWhite || packedChannels != spp)
{
var packed = new ushort[w * h * packedChannels];
var invert = raster.Photometric == PhotometricMinIsWhite;
for (var i = 0; i < w * h; i++)
{
for (var c = 0; c < packedChannels; c++)
{
var v = samples[i * spp + c];
packed[i * packedChannels + c] = invert && c == 0 ? (ushort)(max - v) : v;
}
}
samples = packed;
}
var transfer = o.AssumeLinear || raster.Photometric == PhotometricLinearRaw ? TransferFunction.Linear : TransferFunction.Srgb;
return PixelConvert.FromInterleaved16(samples, w, h, packedChannels, transfer, max, channels);
}
/// <summary>Decodes every strip or tile of <paramref name="ifd"/> into one raster.</summary>
/// <exception cref="InvalidDataException">Missing or inconsistent layout tags, or an unsupported encoding.</exception>
public static TiffRaster ReadRaster(TiffReader reader, Ifd ifd, TiffDecodeOptions? options = null)
{
var o = options ?? TiffDecodeOptions.Default;
var g = Geometry.Read(reader, ifd, o);
var warnings = new List<string>();
var count = g.ChunksPerPlane * g.Planes;
if (count > MaxChunks) throw new InvalidDataException($"TIFF: {count} strips/tiles");
var offsets = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets) ?? throw new InvalidDataException("TIFF: missing strip/tile offsets");
var counts = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts);
if (counts is null && count == 1 && g.Compression == CompressionNone) counts = [(uint)Math.Min(int.MaxValue, g.RowBytes * (long)g.ChunkHeight)];
if (counts is null) throw new InvalidDataException("TIFF: missing strip/tile byte counts");
if (offsets.Length < count || counts.Length < count) warnings.Add($"TIFF: {count} strips/tiles expected, {Math.Min(offsets.Length, counts.Length)} present");
// I/O is sequential (one stream); decoding is parallel.
var chunks = new byte[]?[count];
for (var i = 0; i < Math.Min(count, Math.Min(offsets.Length, counts.Length)); i++)
{
if (counts[i] == 0) continue;
chunks[i] = ReadChunk(reader, offsets[i], counts[i]);
if (chunks[i] is null) warnings.Add($"TIFF: strip/tile {i} lies outside the file");
}
var tables = g.Compression is CompressionJpeg or CompressionLossyJpeg && ifd.Entries.TryGetValue(TiffTags.JpegTables, out var t) ? reader.ReadBytes(t) : null;
var total = (long)g.Width * g.Height * g.Spp;
var ints = g.Format == TiffSampleFormat.UnsignedInteger ? new ushort[total] : null;
var floats = ints is null ? new float[total] : null;
var bits = g.Bps;
var gate = new Lock();
Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }, i =>
{
if (chunks[i] is not { } data) return;
try
{
var decoded = DecodeChunk(g, i, data, tables, ints, floats, reader.LittleEndian);
if (decoded.Warning is { } warning)
{
lock (gate) warnings.Add(warning);
}
if (decoded.Bits > 0) bits = decoded.Bits;
}
catch (InvalidDataException ex)
{
lock (gate) warnings.Add($"TIFF: strip/tile {i}: {ex.Message}");
}
});
var photometric = g.Photometric == PhotometricYCbCr && g.IsJpeg ? PhotometricRgb : g.Photometric;
return new TiffRaster(g.Width, g.Height, g.Spp, bits, g.Format, photometric, ints, floats, warnings);
}
/// <summary>Layout of the image data of one IFD.</summary>
private sealed class Geometry
{
public int Width, Height, Spp, Bps, Compression, Photometric, Planes, ChunkSpp, Predictor, PredictorStride;
public int ChunkWidth, ChunkHeight, Across, ChunksPerPlane;
public long RowBytes;
public bool Tiled, FloatPredictor;
public TiffSampleFormat Format;
public bool IsJpeg => Compression is CompressionJpeg or CompressionLossyJpeg;
public static Geometry Read(TiffReader r, Ifd ifd, TiffDecodeOptions o)
{
var g = new Geometry
{
Width = (int)Math.Min(r.GetUInt(ifd, TiffTags.ImageWidth) ?? 0, int.MaxValue),
Height = (int)Math.Min(r.GetUInt(ifd, TiffTags.ImageLength) ?? 0, int.MaxValue),
Spp = (int)Math.Min(r.GetUInt(ifd, TiffTags.SamplesPerPixel) ?? 1, 64),
Compression = (int)(r.GetUInt(ifd, TiffTags.Compression) ?? CompressionNone),
Predictor = (int)(r.GetUInt(ifd, TiffTags.Predictor) ?? 1),
};
if (g.Width == 0 || g.Height == 0 || g.Spp == 0) throw new InvalidDataException("TIFF: missing or zero image size");
if ((long)g.Width * g.Height * g.Spp > o.MaxSamples) throw new InvalidDataException($"TIFF: {g.Width}x{g.Height}x{g.Spp} exceeds the sample limit");
var bps = r.GetUInts(ifd, TiffTags.BitsPerSample) ?? [1];
if (bps.Length == 0 || bps.Any(b => b != bps[0])) throw new InvalidDataException("TIFF: mixed bits per sample are not supported");
g.Bps = (int)Math.Min(bps[0], 64);
g.Format = (r.GetUInt(ifd, TiffTags.SampleFormat) ?? 1) switch
{
1 => TiffSampleFormat.UnsignedInteger,
3 => TiffSampleFormat.Float,
var f => throw new InvalidDataException($"TIFF: sample format {f} is not supported"),
};
if (g.Format == TiffSampleFormat.Float ? g.Bps is not (16 or 32) : g.Bps is < 1 or > 16)
throw new InvalidDataException($"TIFF: {g.Bps}-bit {g.Format} samples are not supported");
if (g.Compression is not (CompressionNone or CompressionLzw or CompressionJpeg or CompressionDeflate or CompressionAdobeDeflate or CompressionPackBits or CompressionLossyJpeg))
throw new InvalidDataException($"TIFF: compression {g.Compression} is not supported");
if (g.IsJpeg && g.Format == TiffSampleFormat.Float) throw new InvalidDataException("TIFF: JPEG-compressed float data");
g.Photometric = (int)(r.GetUInt(ifd, TiffTags.PhotometricInterpretation) ?? (uint)(g.Spp >= 3 ? PhotometricRgb : 1));
if (g.Photometric == PhotometricYCbCr && !g.IsJpeg) throw new InvalidDataException("TIFF: uncompressed YCbCr is not supported");
// Predictor 2/3 and the DNG 1.4 ×2/×4 variants (34892–34895) differ only in the differencing stride.
(g.FloatPredictor, var factor) = g.Predictor switch
{
1 => (false, 0),
2 => (false, 1),
3 => (true, 1),
34892 => (false, 2),
34893 => (false, 4),
34894 => (true, 2),
34895 => (true, 4),
var p => throw new InvalidDataException($"TIFF: predictor {p} is not supported"),
};
if (factor > 0 && g.FloatPredictor != (g.Format == TiffSampleFormat.Float)) throw new InvalidDataException("TIFF: predictor does not match the sample format");
g.Planes = (r.GetUInt(ifd, TiffTags.PlanarConfiguration) ?? 1) == 2 ? g.Spp : 1;
g.ChunkSpp = g.Planes == 1 ? g.Spp : 1;
g.PredictorStride = g.ChunkSpp * factor;
g.Tiled = ifd.Has(TiffTags.TileWidth) && ifd.Has(TiffTags.TileOffsets);
if (g.Tiled)
{
g.ChunkWidth = (int)Math.Min(r.GetUInt(ifd, TiffTags.TileWidth) ?? 0, 1 << 16);
g.ChunkHeight = (int)Math.Min(r.GetUInt(ifd, TiffTags.TileLength) ?? 0, 1 << 16);
if (g.ChunkWidth == 0 || g.ChunkHeight == 0) throw new InvalidDataException("TIFF: zero tile size");
g.Across = (g.Width + g.ChunkWidth - 1) / g.ChunkWidth;
g.ChunksPerPlane = checked(g.Across * ((g.Height + g.ChunkHeight - 1) / g.ChunkHeight));
}
else
{
g.ChunkWidth = g.Width;
g.ChunkHeight = (int)Math.Clamp(r.GetUInt(ifd, TiffTags.RowsPerStrip) ?? (uint)g.Height, 1, (uint)g.Height);
g.Across = 1;
g.ChunksPerPlane = (g.Height + g.ChunkHeight - 1) / g.ChunkHeight;
}
g.RowBytes = ((long)g.ChunkWidth * g.ChunkSpp * g.Bps + 7) / 8;
if (g.RowBytes * g.ChunkHeight > MaxChunkBytes) throw new InvalidDataException("TIFF: strip/tile too large");
return g;
}
}
private readonly record struct ChunkResult(string? Warning, int Bits);
private static ChunkResult DecodeChunk(Geometry g, int index, byte[] data, byte[]? tables, ushort[]? ints, float[]? floats, bool littleEndian)
{
var plane = index / g.ChunksPerPlane;
var local = index % g.ChunksPerPlane;
var x0 = local % g.Across * g.ChunkWidth;
var y0 = local / g.Across * g.ChunkHeight;
var rows = g.Tiled ? g.ChunkHeight : Math.Min(g.ChunkHeight, g.Height - y0);
var validW = Math.Min(g.ChunkWidth, g.Width - x0);
var validH = Math.Min(rows, g.Height - y0);
if (g.IsJpeg) return DecodeJpegChunk(g, data, tables, ints!, x0, y0, validW, validH, plane);
var expected = (int)(g.RowBytes * rows);
var raw = g.Compression == CompressionNone && data.Length >= expected ? data : new byte[expected];
var produced = g.Compression switch
{
CompressionNone => Copy(data, raw),
CompressionLzw => TiffDecompressors.Lzw(data, raw),
CompressionPackBits => TiffDecompressors.PackBits(data, raw),
_ => TiffDecompressors.Deflate(data, raw),
};
var rowBytes = (int)g.RowBytes;
var rowSamples = g.ChunkWidth * g.ChunkSpp;
var ushorts = ints is null ? null : new ushort[rowSamples];
var singles = floats is null ? null : new float[rowSamples];
for (var r = 0; r < validH; r++)
{
var row = raw.AsSpan(r * rowBytes, rowBytes);
if (ushorts is not null)
{
UnpackIntegers(row, g.Bps, littleEndian, ushorts);
if (g.PredictorStride > 0)
{
var mask = (1 << g.Bps) - 1;
for (var i = g.PredictorStride; i < rowSamples; i++) ushorts[i] = (ushort)((ushorts[i] + ushorts[i - g.PredictorStride]) & mask);
}
Place(ushorts, ints!, g, x0, y0 + r, validW, plane);
}
else
{
UnpackFloats(row, g, littleEndian, singles!);
Place(singles!, floats!, g, x0, y0 + r, validW, plane);
}
}
return new ChunkResult(produced < expected ? $"TIFF: strip/tile {index} truncated ({produced}/{expected} bytes)" : null, 0);
}
private static int Copy(byte[] data, byte[] raw)
{
var n = Math.Min(data.Length, raw.Length);
if (!ReferenceEquals(data, raw)) data.AsSpan(0, n).CopyTo(raw);
return n;
}
/// <summary>Reads one strip/tile; large uncompressed strips (single-strip files) exceed TiffReader's per-read cap
/// and are read in pieces.</summary>
private static byte[]? ReadChunk(TiffReader reader, uint offset, uint length)
{
if (length <= TiffReader.MaxValueBytes) return reader.ReadRelative(offset, (int)length);
if (length > MaxChunkBytes || offset + (long)length > reader.StreamLength - reader.Base) return null;
var result = new byte[length];
for (long done = 0; done < length;)
{
var piece = (int)Math.Min(TiffReader.MaxValueBytes, length - done);
if (reader.ReadRelative(offset + done, piece) is not { } part) return null;
part.CopyTo(result, done);
done += piece;
}
return result;
}
private static void Place<T>(T[] row, T[] target, Geometry g, int x0, int y, int validW, int plane)
{
if (g.Planes == 1)
{
row.AsSpan(0, validW * g.Spp).CopyTo(target.AsSpan((int)(((long)y * g.Width + x0) * g.Spp)));
return;
}
var start = (int)(((long)y * g.Width + x0) * g.Spp + plane);
for (var x = 0; x < validW; x++) target[start + x * g.Spp] = row[x];
}
/// <summary>MSB-first unpacking of 1–16-bit samples (8/16-bit in file byte order).</summary>
private static void UnpackIntegers(ReadOnlySpan<byte> row, int bps, bool littleEndian, ushort[] dst)
{
switch (bps)
{
case 8:
for (var i = 0; i < dst.Length; i++) dst[i] = row[i];
return;
case 16:
for (var i = 0; i < dst.Length; i++)
{
dst[i] = littleEndian ? (ushort)(row[2 * i] | row[2 * i + 1] << 8) : (ushort)(row[2 * i] << 8 | row[2 * i + 1]);
}
return;
}
long bit = 0;
for (var i = 0; i < dst.Length; i++)
{
var v = 0;
for (var b = 0; b < bps; b++, bit++) v = v << 1 | (row[(int)(bit >> 3)] >> (7 - (int)(bit & 7)) & 1);
dst[i] = (ushort)v;
}
}
/// <summary>16/32-bit floats; the floating-point predictor stores byte planes MSB-first after byte differencing.</summary>
private static void UnpackFloats(Span<byte> row, Geometry g, bool littleEndian, float[] dst)
{
var size = g.Bps / 8;
var count = dst.Length;
if (g.PredictorStride > 0)
{
for (var i = g.PredictorStride; i < row.Length; i++) row[i] += row[i - g.PredictorStride];
for (var i = 0; i < count; i++)
{
uint bits = 0;
for (var k = 0; k < size; k++) bits = bits << 8 | row[k * count + i];
dst[i] = size == 4 ? BitConverter.UInt32BitsToSingle(bits) : (float)BitConverter.UInt16BitsToHalf((ushort)bits);
}
return;
}
for (var i = 0; i < count; i++)
{
uint bits = 0;
for (var k = 0; k < size; k++) bits = bits << 8 | row[i * size + (littleEndian ? size - 1 - k : k)];
dst[i] = size == 4 ? BitConverter.UInt32BitsToSingle(bits) : (float)BitConverter.UInt16BitsToHalf((ushort)bits);
}
}
private static ChunkResult DecodeJpegChunk(Geometry g, byte[] data, byte[]? tables, ushort[] ints, int x0, int y0, int validW, int validH, int plane)
{
var options = new JpegDecodeOptions
{
Tables = tables,
MaxDegreeOfParallelism = 1,
ColorTransform = g.Photometric switch
{
PhotometricYCbCr => JpegColorTransform.YCbCr,
PhotometricRgb when g.Compression == CompressionJpeg => JpegColorTransform.None,
_ => JpegColorTransform.Auto,
},
};
var (image, raw) = JpegDecoder.DecodeTile(data, options);
string? warning = null;
if (image is not null)
{
var comps = Math.Min(image.Components, g.ChunkSpp);
var w = Math.Min(validW, image.Width);
for (var r = 0; r < Math.Min(validH, image.Height); r++)
{
for (var x = 0; x < w; x++)
{
var src = (r * image.Width + x) * image.Components;
var dst = ((long)(y0 + r) * g.Width + x0 + x) * g.Spp + plane;
for (var c = 0; c < comps; c++) ints[dst + c] = image.Pixels8 is { } p8 ? p8[src + c] : image.Pixels16![src + c];
}
}
if (image.Warnings.Count > 0) warning = "TIFF: " + image.Warnings[0];
return new ChunkResult(warning, image.BitDepth);
}
// Lossless: the JPEG frame may be shaped differently from the tile (DNG writes e.g. 2 components × width/2),
// but the sample stream order is the same, so samples map back linearly.
var samples = raw.Samples;
var perRow = g.ChunkWidth * g.ChunkSpp;
var tileSamples = (long)perRow * g.ChunkHeight;
if (samples.Length != tileSamples) warning = $"TIFF: lossless JPEG holds {samples.Length} samples, tile needs {tileSamples}";
var n = (int)Math.Min(samples.Length, tileSamples);
for (var k = 0; k < n; k++)
{
var r = k / perRow;
var rem = k - r * perRow;
var x = rem / g.ChunkSpp;
if (r >= validH) break;
if (x >= validW) continue;
ints[((long)(y0 + r) * g.Width + x0 + x) * g.Spp + plane + rem % g.ChunkSpp] = samples[k];
}
return new ChunkResult(warning, raw.Precision);
}
}
+222
View File
@@ -0,0 +1,222 @@
using System.Buffers;
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Imaging;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Codecs.Tiff;
/// <summary>Compression written by <see cref="TiffWriter"/>.</summary>
public enum TiffCompression
{
None = 1,
Deflate = 8,
}
/// <summary>Options for <see cref="TiffWriter"/>.</summary>
public sealed record TiffWriteOptions
{
public static TiffWriteOptions Default { get; } = new();
/// <summary>8 or 16.</summary>
public int BitsPerSample { get; init; } = 16;
public TiffCompression Compression { get; init; } = TiffCompression.Deflate;
/// <summary>Horizontal differencing (Predictor = 2) before Deflate; ignored when uncompressed.</summary>
public bool Predictor { get; init; } = true;
/// <summary>Encoding of <see cref="ImageBuffer"/> input: sRGB (display-ready) or linear light.</summary>
public TransferFunction Transfer { get; init; } = TransferFunction.Srgb;
public CompressionLevel Level { get; init; } = CompressionLevel.Optimal;
/// <summary>TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded.</summary>
public byte[]? Exif { get; init; }
/// <summary>Worker limit for strip encoding (-1 = all cores).</summary>
public int MaxDegreeOfParallelism { get; init; } = -1;
}
/// <summary>
/// Little-endian baseline TIFF writer: 8/16-bit gray, RGB or RGBA (unassociated alpha), uncompressed or Deflate with
/// optional horizontal predictor, optional embedded Exif. Strips are encoded in parallel and written in order.
/// </summary>
public static class TiffWriter
{
private const int TargetStripBytes = 256 * 1024;
public static byte[] Write(ImageBuffer image, TiffWriteOptions? options = null)
{
using var ms = new MemoryStream();
Write(ms, image, options);
return ms.ToArray();
}
/// <summary>Writes a linear-light buffer (1 channel → gray, 3 → RGB, 4 → RGBA).</summary>
public static void Write(Stream output, ImageBuffer image, TiffWriteOptions? options = null)
{
var o = options ?? TiffWriteOptions.Default;
var channels = image.Channels;
Write(output, image.Width, image.Height, channels, o, (y, row) =>
{
if (o.BitsPerSample == 16)
{
PixelConvert.EncodeRow16(image, y, row, channels, o.Transfer);
return;
}
var buffer = ArrayPool<byte>.Shared.Rent(row.Length);
PixelConvert.EncodeRow8(image, y, buffer.AsSpan(0, row.Length), channels, o.Transfer, dither: false);
for (var i = 0; i < row.Length; i++) row[i] = buffer[i];
ArrayPool<byte>.Shared.Return(buffer);
});
}
/// <summary>Writes interleaved, already-encoded samples (values below 2^<see cref="TiffWriteOptions.BitsPerSample"/>).</summary>
public static unsafe void Write(Stream output, ReadOnlySpan<ushort> samples, int width, int height, int channels, TiffWriteOptions? options = null)
{
if (samples.Length < (long)width * height * channels) throw new ArgumentException("Sample buffer too small", nameof(samples));
fixed (ushort* p = samples)
{
var ptr = (nint)p;
Write(output, width, height, channels, options ?? TiffWriteOptions.Default,
(y, row) => new ReadOnlySpan<ushort>((ushort*)ptr + (long)y * width * channels, width * channels).CopyTo(row));
}
}
private delegate void RowSource(int y, Span<ushort> row);
private static void Write(Stream output, int width, int height, int channels, TiffWriteOptions o, RowSource source)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
if (channels is < 1 or > 4 or 2) throw new ArgumentOutOfRangeException(nameof(channels), "1, 3 or 4 channels");
if (o.BitsPerSample is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(o), "8 or 16 bits per sample");
if (!output.CanSeek)
{
using var buffer = new MemoryStream();
Write(buffer, width, height, channels, o, source);
buffer.Position = 0;
buffer.CopyTo(output);
return;
}
var start = output.Position;
output.Write("II*\0\0\0\0\0"u8);
var bytesPerSample = o.BitsPerSample / 8;
var rowBytes = (long)width * channels * bytesPerSample;
var rowsPerStrip = (int)Math.Clamp(TargetStripBytes / rowBytes, 1, height);
var strips = (height + rowsPerStrip - 1) / rowsPerStrip;
var deflate = o.Compression == TiffCompression.Deflate;
var predictor = deflate && o.Predictor;
var offsets = new uint[strips];
var counts = new uint[strips];
var batch = Math.Max(1, Environment.ProcessorCount * 2);
var encoded = new byte[batch][];
var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism };
for (var first = 0; first < strips; first += batch)
{
var n = Math.Min(batch, strips - first);
Parallel.For(0, n, parallel, k =>
{
var s = first + k;
var y0 = s * rowsPerStrip;
var rows = Math.Min(rowsPerStrip, height - y0);
var raw = new byte[rowBytes * rows];
var row = new ushort[width * channels];
for (var r = 0; r < rows; r++)
{
source(y0 + r, row);
if (predictor)
{
var mask = (1 << o.BitsPerSample) - 1;
for (var i = row.Length - 1; i >= channels; i--) row[i] = (ushort)((row[i] - row[i - channels]) & mask);
}
var dst = raw.AsSpan((int)(r * rowBytes), (int)rowBytes);
if (bytesPerSample == 2)
{
for (var i = 0; i < row.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(dst[(2 * i)..], row[i]);
}
else
{
for (var i = 0; i < row.Length; i++) dst[i] = (byte)row[i];
}
}
encoded[k] = deflate ? Deflate(raw, o.Level) : raw;
});
for (var k = 0; k < n; k++)
{
if (output.Position - start > uint.MaxValue - (long)encoded[k].Length) throw new InvalidOperationException("TIFF exceeds 4 GB");
offsets[first + k] = (uint)(output.Position - start);
counts[first + k] = (uint)encoded[k].Length;
output.Write(encoded[k]);
}
}
var ifd = new TiffDirectory();
ifd.Long(TiffTags.NewSubfileType, 0);
ifd.Long(TiffTags.ImageWidth, (uint)width);
ifd.Long(TiffTags.ImageLength, (uint)height);
ifd.Short(TiffTags.BitsPerSample, Enumerable.Repeat((ushort)o.BitsPerSample, channels).ToArray());
ifd.Short(TiffTags.Compression, (ushort)o.Compression);
ifd.Short(TiffTags.PhotometricInterpretation, channels == 1 ? (ushort)1 : (ushort)2);
ifd.Long(TiffTags.StripOffsets, offsets);
ifd.Short(TiffTags.SamplesPerPixel, (ushort)channels);
ifd.Long(TiffTags.RowsPerStrip, (uint)rowsPerStrip);
ifd.Long(TiffTags.StripByteCounts, counts);
ifd.Rational(TiffTags.XResolution, (72u, 1u));
ifd.Rational(TiffTags.YResolution, (72u, 1u));
ifd.Short(TiffTags.PlanarConfiguration, 1);
ifd.Short(TiffTags.ResolutionUnit, 2);
ifd.Ascii(TiffTags.Software, "Titano");
if (predictor) ifd.Short(TiffTags.Predictor, 2);
if (channels == 4) ifd.Short(TiffTags.ExtraSamples, 2);
if (o.Exif is { } exif) ifd.AttachExif(exif);
WriteDirectory(output, start, ifd);
}
/// <summary>Appends <paramref name="ifd"/> (and its children) and points the header at it.</summary>
internal static void WriteDirectory(Stream output, long start, TiffDirectory ifd)
{
var at = output.Position - start;
ifd.Layout(at);
var origin = new OffsetStream(output, start);
ifd.Write(origin);
var end = output.Position;
output.Position = start + 4;
Span<byte> pointer = stackalloc byte[4];
BinaryPrimitives.WriteUInt32LittleEndian(pointer, (uint)((at + 1) & ~1L));
output.Write(pointer);
output.Position = end;
}
internal static byte[] Deflate(byte[] raw, CompressionLevel level)
{
using var ms = new MemoryStream(raw.Length / 2 + 64);
using (var z = new ZLibStream(ms, level, leaveOpen: true)) z.Write(raw);
return ms.ToArray();
}
/// <summary>View of a stream whose Position is relative to the TIFF header (files may start mid-stream).</summary>
private sealed class OffsetStream(Stream inner, long origin) : Stream
{
public override bool CanRead => false;
public override bool CanSeek => true;
public override bool CanWrite => true;
public override long Length => inner.Length - origin;
public override long Position
{
get => inner.Position - origin;
set => inner.Position = value + origin;
}
public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
public override void Write(ReadOnlySpan<byte> buffer) => inner.Write(buffer);
public override void WriteByte(byte value) => inner.WriteByte(value);
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 seekOrigin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
}
}
+383
View File
@@ -0,0 +1,383 @@
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
namespace Titano.Core.Imaging;
/// <summary>How integer samples relate to light: sRGB-encoded (display referred) or proportional to linear light.</summary>
public enum TransferFunction
{
Srgb,
Linear,
}
/// <summary>
/// Conversions between interleaved integer pixels and planar linear-light <see cref="ImageBuffer"/>s, gray ↔ RGB,
/// Exif orientation, and clamping. Interleaved layouts: 1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA. Alpha is
/// never transfer-encoded. Row loops are parallel for large images.
/// </summary>
public static class PixelConvert
{
private const int ParallelThreshold = 1 << 16;
/// <summary>8×8 Bayer thresholds in code units, centred on zero (ordered dither).</summary>
private static readonly float[] Bayer = BuildBayer();
/// <summary>Interleaved 8-bit samples → linear buffer.</summary>
/// <param name="outputChannels">0 = natural (1/2 → 1, 3 → 3, 4 → 3); 3 expands gray; 4 keeps alpha.</param>
public static ImageBuffer FromInterleaved8(ReadOnlySpan<byte> pixels, int width, int height, int channels, TransferFunction transfer = TransferFunction.Srgb, int outputChannels = 0)
{
var outCh = OutputChannels(channels, outputChannels);
CheckLength(pixels.Length, width, height, channels);
var lut = new float[256];
for (var i = 0; i < 256; i++) lut[i] = transfer == TransferFunction.Srgb ? ColorSpace.Linear8((byte)i) : i / 255f;
var image = new ImageBuffer(width, height, outCh, clear: false);
unsafe
{
fixed (byte* p = pixels)
{
var ptr = (nint)p;
ForRows(height, width, y =>
{
var row = new ReadOnlySpan<byte>((byte*)ptr + (long)y * width * channels, width * channels);
Scatter(row, image, y, channels, lut, 1f / 255f);
});
}
}
return image;
}
/// <summary>Interleaved 16-bit container samples (values 0..<paramref name="maxValue"/>) → linear buffer.</summary>
public static ImageBuffer FromInterleaved16(ReadOnlySpan<ushort> pixels, int width, int height, int channels, TransferFunction transfer = TransferFunction.Srgb, int maxValue = 65535, int outputChannels = 0)
{
if (maxValue is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(maxValue));
var outCh = OutputChannels(channels, outputChannels);
CheckLength(pixels.Length, width, height, channels);
var lut = new float[maxValue + 1];
for (var i = 0; i <= maxValue; i++)
{
lut[i] = transfer == TransferFunction.Linear ? i / (float)maxValue
: maxValue == 65535 ? ColorSpace.Linear16((ushort)i) : (float)ColorSpace.SrgbToLinear(i / (double)maxValue);
}
var alphaScale = 1f / maxValue;
var image = new ImageBuffer(width, height, outCh, clear: false);
unsafe
{
fixed (ushort* p = pixels)
{
var ptr = (nint)p;
ForRows(height, width, y =>
{
var row = new ReadOnlySpan<ushort>((ushort*)ptr + (long)y * width * channels, width * channels);
Scatter(row, image, y, channels, lut, alphaScale);
});
}
}
return image;
}
/// <summary>Linear buffer → interleaved 8-bit samples with <paramref name="channels"/> per pixel
/// (1 from RGB takes Rec.709 luminance; missing alpha is opaque).</summary>
/// <param name="dither">Add 8×8 ordered dither before rounding (breaks banding in smooth gradients).</param>
public static void ToInterleaved8(ImageBuffer image, Span<byte> destination, int channels, TransferFunction transfer = TransferFunction.Srgb, bool dither = false)
{
CheckLength(destination.Length, image.Width, image.Height, channels);
unsafe
{
fixed (byte* p = destination)
{
var ptr = (nint)p;
ForRows(image.Height, image.Width, y =>
{
var row = new Span<byte>((byte*)ptr + (long)y * image.Width * channels, image.Width * channels);
EncodeRow8(image, y, row, channels, transfer, dither);
});
}
}
}
/// <summary>Allocating overload of <see cref="ToInterleaved8(ImageBuffer, Span{byte}, int, TransferFunction, bool)"/>.</summary>
public static byte[] ToInterleaved8(ImageBuffer image, int channels, TransferFunction transfer = TransferFunction.Srgb, bool dither = false)
{
var result = new byte[checked(image.Width * image.Height * channels)];
ToInterleaved8(image, result, channels, transfer, dither);
return result;
}
/// <summary>Linear buffer → interleaved 16-bit samples (0..65535).</summary>
public static void ToInterleaved16(ImageBuffer image, Span<ushort> destination, int channels, TransferFunction transfer = TransferFunction.Srgb)
{
CheckLength(destination.Length, image.Width, image.Height, channels);
unsafe
{
fixed (ushort* p = destination)
{
var ptr = (nint)p;
ForRows(image.Height, image.Width, y =>
{
var row = new Span<ushort>((ushort*)ptr + (long)y * image.Width * channels, image.Width * channels);
EncodeRow16(image, y, row, channels, transfer);
});
}
}
}
/// <summary>Allocating overload of <see cref="ToInterleaved16(ImageBuffer, Span{ushort}, int, TransferFunction)"/>.</summary>
public static ushort[] ToInterleaved16(ImageBuffer image, int channels, TransferFunction transfer = TransferFunction.Srgb)
{
var result = new ushort[checked(image.Width * image.Height * channels)];
ToInterleaved16(image, result, channels, transfer);
return result;
}
/// <summary>Encodes row <paramref name="y"/> into interleaved 8-bit samples (codec edge helper).</summary>
internal static void EncodeRow8(ImageBuffer image, int y, Span<byte> row, int channels, TransferFunction transfer, bool dither)
{
Span<float> offsets = stackalloc float[8];
for (var i = 0; i < 8; i++) offsets[i] = dither ? 0.5f + Bayer[(y & 7) * 8 + i] : 0.5f;
var srgb = transfer == TransferFunction.Srgb;
var scratch = channels <= 2 && image.Channels >= 3 ? ArrayPool<float>.Shared.Rent(image.Width) : null;
for (var c = 0; c < channels; c++)
{
if (c == (channels <= 2 ? 1 : 3))
{
var a = image.Channels == 4 ? image.Row(3, y) : default;
for (var x = 0; x < image.Width; x++) row[x * channels + c] = a.IsEmpty ? (byte)255 : (byte)(Math.Clamp(a[x], 0f, 1f) * 255f + 0.5f);
continue;
}
var src = ColourRow(image, y, c, channels, scratch);
for (var x = 0; x < src.Length; x++)
{
var e = srgb ? ColorSpace.EncodeFast(src[x]) : Math.Clamp(src[x], 0f, 1f);
row[x * channels + c] = (byte)Math.Clamp(e * 255f + offsets[x & 7], 0f, 255f);
}
}
if (scratch is not null) ArrayPool<float>.Shared.Return(scratch);
}
/// <summary>Encodes row <paramref name="y"/> into interleaved 16-bit samples (codec edge helper).</summary>
internal static void EncodeRow16(ImageBuffer image, int y, Span<ushort> row, int channels, TransferFunction transfer)
{
var srgb = transfer == TransferFunction.Srgb;
var scratch = channels <= 2 && image.Channels >= 3 ? ArrayPool<float>.Shared.Rent(image.Width) : null;
for (var c = 0; c < channels; c++)
{
if (c == (channels <= 2 ? 1 : 3))
{
var a = image.Channels == 4 ? image.Row(3, y) : default;
for (var x = 0; x < image.Width; x++) row[x * channels + c] = a.IsEmpty ? (ushort)65535 : (ushort)(Math.Clamp(a[x], 0f, 1f) * 65535f + 0.5f);
continue;
}
var src = ColourRow(image, y, c, channels, scratch);
for (var x = 0; x < src.Length; x++)
{
row[x * channels + c] = srgb ? ColorSpace.Encode16(src[x]) : (ushort)(Math.Clamp(src[x], 0f, 1f) * 65535f + 0.5f);
}
}
if (scratch is not null) ArrayPool<float>.Shared.Return(scratch);
}
/// <summary>Single-channel buffer replicated into three channels.</summary>
public static ImageBuffer GrayToRgb(ImageBuffer gray)
{
if (gray.Channels != 1) throw new ArgumentException("Expected one channel", nameof(gray));
var rgb = new ImageBuffer(gray.Width, gray.Height, 3, clear: false);
for (var c = 0; c < 3; c++) gray.Plane(0).CopyTo(rgb.Plane(c));
return rgb;
}
/// <summary>Rec.709 luminance of an RGB(A) buffer.</summary>
public static ImageBuffer RgbToGray(ImageBuffer rgb)
{
if (rgb.Channels < 3) throw new ArgumentException("Expected RGB", nameof(rgb));
var gray = new ImageBuffer(rgb.Width, rgb.Height, 1, clear: false);
var r = rgb.Plane(0);
var g = rgb.Plane(1);
var b = rgb.Plane(2);
var d = gray.Plane(0);
var i = 0;
if (Vector.IsHardwareAccelerated)
{
var wr = new Vector<float>(ColorSpace.LumaR);
var wg = new Vector<float>(ColorSpace.LumaG);
var wb = new Vector<float>(ColorSpace.LumaB);
for (; i <= d.Length - Vector<float>.Count; i += Vector<float>.Count)
{
(new Vector<float>(r[i..]) * wr + new Vector<float>(g[i..]) * wg + new Vector<float>(b[i..]) * wb).CopyTo(d[i..]);
}
}
for (; i < d.Length; i++) d[i] = ColorSpace.Luminance(r[i], g[i], b[i]);
return gray;
}
/// <summary>Clamps every value into [<paramref name="min"/>, <paramref name="max"/>] (NaN becomes <paramref name="min"/>).</summary>
public static void Clamp(Span<float> values, float min = 0f, float max = 1f)
{
var i = 0;
if (Vector.IsHardwareAccelerated)
{
var lo = new Vector<float>(min);
var hi = new Vector<float>(max);
for (; i <= values.Length - Vector<float>.Count; i += Vector<float>.Count)
{
var v = new Vector<float>(values[i..]);
// Max(v, lo) with v as the first operand maps NaN to lo on x86 (maxps returns the second operand).
Vector.Min(Vector.ConditionalSelect(Vector.Equals(v, v), Vector.Max(v, lo), lo), hi).CopyTo(values[i..]);
}
}
for (; i < values.Length; i++)
{
var v = values[i];
values[i] = float.IsNaN(v) ? min : Math.Clamp(v, min, max);
}
}
/// <summary>Size after applying an Exif orientation (5–8 swap width and height).</summary>
public static (int Width, int Height) OrientedSize(int width, int height, int orientation) =>
orientation is >= 5 and <= 8 ? (height, width) : (width, height);
/// <summary>Applies an Exif orientation (1–8) into a new buffer; other values are treated as 1 (copy).</summary>
public static ImageBuffer ApplyOrientation(ImageBuffer source, int orientation)
{
int w = source.Width, h = source.Height;
var (ow, oh) = OrientedSize(w, h, orientation);
var result = new ImageBuffer(ow, oh, source.Channels, clear: false);
if (orientation is < 2 or > 8)
{
source.CopyTo(result);
return result;
}
for (var c = 0; c < source.Channels; c++)
{
var src = source.Storage.AsMemory(c * source.PlaneLength, source.PlaneLength);
var dst = result.Storage.AsMemory(c * result.PlaneLength, result.PlaneLength);
if (orientation <= 4)
{
ForRows(oh, ow, y =>
{
var sy = orientation is 3 or 4 ? h - 1 - y : y;
var s = src.Span.Slice(sy * w, w);
var d = dst.Span.Slice(y * ow, ow);
s.CopyTo(d);
if (orientation is 2 or 3) d.Reverse();
});
continue;
}
// Transposing orientations: copy in 32×32 tiles so both sides stay cache-friendly.
const int tile = 32;
var tilesY = (oh + tile - 1) / tile;
ForRows(tilesY, ow * tile, ty =>
{
var s = src.Span;
var d = dst.Span;
var y1 = Math.Min(oh, (ty + 1) * tile);
for (var x0 = 0; x0 < ow; x0 += tile)
{
var x1 = Math.Min(ow, x0 + tile);
for (var y = ty * tile; y < y1; y++)
{
for (var x = x0; x < x1; x++)
{
var (sx, sy) = orientation switch
{
5 => (y, x),
6 => (y, h - 1 - x),
7 => (w - 1 - y, h - 1 - x),
_ => (w - 1 - y, x),
};
d[y * ow + x] = s[sy * w + sx];
}
}
}
});
}
return result;
}
/// <summary>Linear row feeding output colour channel <paramref name="c"/>: gray is replicated, and a gray output
/// from RGB takes Rec.709 luminance computed into <paramref name="scratch"/>.</summary>
private static ReadOnlySpan<float> ColourRow(ImageBuffer image, int y, int c, int channels, float[]? scratch)
{
if (image.Channels == 1) return image.Row(0, y);
if (scratch is null) return image.Row(c, y);
var r = image.Row(0, y);
var g = image.Row(1, y);
var b = image.Row(2, y);
var luminance = scratch.AsSpan(0, image.Width);
for (var x = 0; x < luminance.Length; x++) luminance[x] = ColorSpace.Luminance(r[x], g[x], b[x]);
return luminance;
}
/// <summary>De-interleaves one row: colour through <paramref name="lut"/> (indices clamped to its range), alpha scaled.</summary>
private static void Scatter<T>(ReadOnlySpan<T> row, ImageBuffer image, int y, int channels, float[] lut, float alphaScale)
where T : unmanaged, IBinaryInteger<T>
{
var w = image.Width;
var top = lut.Length - 1;
var colour = channels is 1 or 2 ? 1 : 3;
for (var c = 0; c < image.Channels; c++)
{
var dst = image.Row(c, y);
if (c == 3)
{
if (channels is 2 or 4)
{
var a = channels - 1;
for (var x = 0; x < w; x++) dst[x] = Math.Min(int.CreateTruncating(row[x * channels + a]), top) * alphaScale;
}
else
{
dst.Fill(1f);
}
continue;
}
var s = colour == 1 ? 0 : c;
for (var x = 0; x < w; x++) dst[x] = lut[Math.Min(int.CreateTruncating(row[x * channels + s]), top)];
}
}
private static int OutputChannels(int channels, int requested)
{
if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels));
if (requested is not (0 or 1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(requested));
if (requested == 1 && channels > 2) throw new ArgumentException("Use RgbToGray to reduce colour to one channel", nameof(requested));
return requested != 0 ? requested : channels <= 2 ? 1 : 3;
}
private static void CheckLength(int length, int width, int height, int channels)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels));
if (length < (long)width * height * channels) throw new ArgumentException("Pixel buffer too small");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ForRows(int rows, int rowWork, Action<int> body)
{
if ((long)rows * rowWork < ParallelThreshold)
{
for (var y = 0; y < rows; y++) body(y);
}
else
{
Parallel.For(0, rows, body);
}
}
private static float[] BuildBayer()
{
// Recursive Bayer matrix: interleave bits of (x ^ y) and y, least significant coordinate bits first.
var m = new float[64];
for (var y = 0; y < 8; y++)
{
for (var x = 0; x < 8; x++)
{
var v = 0;
for (var bit = 0; bit < 3; bit++) v = v << 2 | (((x ^ y) >> bit) & 1) << 1 | ((y >> bit) & 1);
m[y * 8 + x] = (v + 0.5f) / 64f - 0.5f;
}
}
return m;
}
}
+201
View File
@@ -0,0 +1,201 @@
using System.Numerics;
namespace Titano.Core.Imaging;
/// <summary>Reconstruction filters for <see cref="Resampler"/>.</summary>
public enum ResampleFilter
{
/// <summary>Lanczos3 on axes that shrink, Catmull-Rom on axes that grow.</summary>
Auto,
/// <summary>Exact area average (no ringing; fastest for large reductions such as thumbnails).</summary>
Box,
Lanczos3,
CatmullRom,
}
/// <summary>
/// Separable two-pass resampling of linear-light <see cref="ImageBuffer"/>s. When shrinking, the kernel is stretched
/// by the reduction factor (proper low-pass support); weights are normalised and folded at the edges (clamp), so
/// constant images stay constant and mean energy is preserved. Rows are processed in parallel.
/// </summary>
public static class Resampler
{
/// <summary>Resizes into a new buffer with the same channel count.</summary>
public static ImageBuffer Resize(ImageBuffer source, int width, int height, ResampleFilter filter = ResampleFilter.Auto, int maxDegreeOfParallelism = -1)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
var parallel = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism };
if (width == source.Width && height == source.Height) return source.Clone();
var wx = width == source.Width ? null : Weights.Build(source.Width, width, filter);
var wy = height == source.Height ? null : Weights.Build(source.Height, height, filter);
if (wx is null) return Vertical(source, wy!, parallel);
if (wy is null) return Horizontal(source, wx, parallel);
// Run the pass that leaves the smaller intermediate work first.
var horizontalFirst = (long)source.Height * width * wx.Stride + (long)height * width * wy.Stride
<= (long)height * source.Width * wy.Stride + (long)height * width * wx.Stride;
using var intermediate = horizontalFirst ? Horizontal(source, wx, parallel) : Vertical(source, wy, parallel);
return horizontalFirst ? Vertical(intermediate, wy, parallel) : Horizontal(intermediate, wx, parallel);
}
/// <summary>Area-average reduction so that the long edge is at most <paramref name="maxLongEdge"/>
/// (a copy when the image is already small enough).</summary>
public static ImageBuffer Thumbnail(ImageBuffer source, int maxLongEdge)
{
var (w, h) = FitWithin(source.Width, source.Height, maxLongEdge);
return w == source.Width && h == source.Height ? source.Clone() : Resize(source, w, h, ResampleFilter.Box);
}
/// <summary>Largest size with the same aspect ratio whose long edge is ≤ <paramref name="maxLongEdge"/> (never upscales).</summary>
public static (int Width, int Height) FitWithin(int width, int height, int maxLongEdge)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLongEdge);
var longEdge = Math.Max(width, height);
if (longEdge <= maxLongEdge) return (width, height);
var scale = maxLongEdge / (double)longEdge;
return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
}
private static ImageBuffer Horizontal(ImageBuffer source, Weights w, ParallelOptions parallel)
{
var result = new ImageBuffer(w.Length, source.Height, source.Channels, clear: false);
Parallel.For(0, source.Height, parallel, y =>
{
for (var c = 0; c < source.Channels; c++)
{
ReadOnlySpan<float> src = source.Row(c, y);
var dst = result.Row(c, y);
for (var x = 0; x < dst.Length; x++)
{
dst[x] = Dot(src.Slice(w.Start[x], w.Count[x]), w.Values.AsSpan(x * w.Stride, w.Count[x]));
}
}
});
return result;
}
private static ImageBuffer Vertical(ImageBuffer source, Weights w, ParallelOptions parallel)
{
var result = new ImageBuffer(source.Width, w.Length, source.Channels, clear: false);
Parallel.For(0, w.Length, parallel, y =>
{
var taps = w.Values.AsSpan(y * w.Stride, w.Count[y]);
for (var c = 0; c < source.Channels; c++)
{
var dst = result.Row(c, y);
dst.Clear();
for (var k = 0; k < taps.Length; k++) MultiplyAdd(source.Row(c, w.Start[y] + k), taps[k], dst);
}
});
return result;
}
private static float Dot(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
{
var i = 0;
var sum = 0f;
if (Vector.IsHardwareAccelerated && a.Length >= Vector<float>.Count)
{
var acc = Vector<float>.Zero;
for (; i <= a.Length - Vector<float>.Count; i += Vector<float>.Count) acc += new Vector<float>(a[i..]) * new Vector<float>(b[i..]);
sum = Vector.Sum(acc);
}
for (; i < a.Length; i++) sum += a[i] * b[i];
return sum;
}
private static void MultiplyAdd(ReadOnlySpan<float> src, float weight, Span<float> dst)
{
var i = 0;
if (Vector.IsHardwareAccelerated)
{
var w = new Vector<float>(weight);
for (; i <= dst.Length - Vector<float>.Count; i += Vector<float>.Count) (new Vector<float>(dst[i..]) + new Vector<float>(src[i..]) * w).CopyTo(dst[i..]);
}
for (; i < dst.Length; i++) dst[i] += src[i] * weight;
}
/// <summary>Per output sample: a contiguous source range and its normalised weights (stride-padded).</summary>
private sealed class Weights
{
public required int Length { get; init; }
public required int Stride { get; init; }
public required int[] Start { get; init; }
public required int[] Count { get; init; }
public required float[] Values { get; init; }
public static Weights Build(int source, int target, ResampleFilter filter)
{
var scale = target / (double)source;
var kind = filter == ResampleFilter.Auto ? (scale < 1 ? ResampleFilter.Lanczos3 : ResampleFilter.CatmullRom) : filter;
var radius = kind switch { ResampleFilter.Lanczos3 => 3.0, ResampleFilter.CatmullRom => 2.0, _ => 0.5 };
var stretch = Math.Max(1.0, 1 / scale);
var stride = (int)Math.Ceiling(2 * radius * stretch) + 2;
var start = new int[target];
var count = new int[target];
var values = new float[target * stride];
var taps = new double[source];
for (var i = 0; i < target; i++)
{
double lo, hi;
if (kind == ResampleFilter.Box)
{
lo = i / scale;
hi = (i + 1) / scale;
}
else
{
var center = (i + 0.5) / scale;
lo = center - radius * stretch;
hi = center + radius * stretch;
}
int first = Math.Max(0, (int)Math.Floor(lo) - 1), last = Math.Min(source - 1, (int)Math.Ceiling(hi));
int left = (int)Math.Floor(lo) - 1, right = (int)Math.Ceiling(hi);
Array.Clear(taps, first, last - first + 1);
var sum = 0.0;
for (var j = left; j <= right; j++)
{
double weight;
if (kind == ResampleFilter.Box)
{
weight = Math.Max(0, Math.Min(hi, j + 1) - Math.Max(lo, j));
}
else
{
var x = (j + 0.5 - (i + 0.5) / scale) / stretch;
weight = kind == ResampleFilter.Lanczos3 ? Lanczos3(x) : CatmullRom(x);
}
if (weight == 0) continue;
taps[Math.Clamp(j, 0, source - 1)] += weight; // clamp-to-edge folds outside taps inward
sum += weight;
}
while (first < last && taps[first] == 0) first++;
while (last > first && taps[last] == 0) last--;
start[i] = first;
count[i] = last - first + 1;
for (var j = first; j <= last; j++) values[i * stride + j - first] = (float)(taps[j] / sum);
}
return new Weights { Length = target, Stride = stride, Start = start, Count = count, Values = values };
}
private static double Lanczos3(double x)
{
x = Math.Abs(x);
if (x < 1e-9) return 1;
if (x >= 3) return 0;
var px = Math.PI * x;
return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px);
}
private static double CatmullRom(double x)
{
x = Math.Abs(x);
return x < 1 ? (1.5 * x - 2.5) * x * x + 1
: x < 2 ? ((-0.5 * x + 2.5) * x - 4) * x + 2
: 0;
}
}
}