diff --git a/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/EncodeBenchmark.cs b/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/EncodeBenchmark.cs index 1964178..9c472a4 100644 --- a/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/EncodeBenchmark.cs +++ b/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/EncodeBenchmark.cs @@ -1,6 +1,8 @@ +using System.Buffers; using System.Diagnostics; using System.Globalization; using System.Reflection; +using Sdcb.SimdCodecs.Abstractions; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; @@ -85,6 +87,13 @@ private static bool RunMode(string mode, List images, int reps, bool gate contestants.Insert(1, new("baseline", baseline)); if (mode == "baseline") { + // The same encoder through the streaming session, fed 16-row bands: its bytes must equal "ours". + var sink = new ArrayBufferWriter(); + contestants.Insert(1, new("streamed", (img, c) => EncodeStreamed(sink, img, new JpegEncodeOptions + { + Quality = c.Quality, + Subsampling = c.Subsample420 ? JpegSubsampling.Chroma420 : JpegSubsampling.Chroma444, + }))); contestants.Add(new("ImageSharp", (img, c) => { using var image = SixLabors.ImageSharp.Image.LoadPixelData(img.Rgb, img.Width, img.Height); @@ -120,10 +129,14 @@ private static bool RunMode(string mode, List images, int reps, bool gate var tallies = contestants.ToDictionary(c => c.Name, _ => new Tally()); foreach (var image in images) { + byte[] oursJpeg = []; foreach (var c in contestants) { var t = tallies[c.Name]; var jpeg = c.Encode(image, config); // also the warm-up + if (c.Name == "ours") oursJpeg = jpeg; + else if (c.Name == "streamed" && !jpeg.AsSpan().SequenceEqual(oursJpeg)) + throw new InvalidOperationException($"{image.Name} {config}: the streaming session's bytes differ from JpegEncoder.Encode's"); var times = new double[reps]; for (var r = 0; r < reps; r++) { @@ -167,6 +180,22 @@ private static bool RunMode(string mode, List images, int reps, bool gate return ok; } + /// Encodes through 's streaming session, 16 rows per WriteRows. + private static byte[] EncodeStreamed(ArrayBufferWriter sink, Image img, JpegEncodeOptions options) + { + sink.ResetWrittenCount(); + using var session = JpegImageEncoder.Create(sink, options); + var frame = session.AddFrame(img.Width, img.Height, PixelFormat.Rgb24); + var rowBytes = img.Width * 3; + for (var y = 0; y < img.Height; y += 16) + { + var n = Math.Min(16, img.Height - y); + frame.WriteRows(img.Rgb.AsSpan(y * rowBytes, n * rowBytes), n); + } + session.Commit(); + return sink.WrittenSpan.ToArray(); + } + // ---------------------------------------------------------------- inputs private static List LoadMasters(int maxDim) diff --git a/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/README.md b/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/README.md index 1cc0512..a194f2a 100644 --- a/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/README.md +++ b/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/README.md @@ -95,3 +95,15 @@ Recorded on a Ryzen 7 5800X, Windows 11, .NET 10.0.11, AVX2 (no AVX-512), MP/s: | q95 4:4:4 | 266 | 262 | 139 | 144 / 96 | 51 / 42 | At the same quality our files are 0.2–2.3% smaller than libjpeg-turbo's in every mode and PSNR-Y is 0.004–0.09 dB higher (float AAN DCT, unrounded colour conversion). + +In `baseline` mode a `streamed` row is the same encoder through `JpegImageEncoder`'s streaming session, fed 16-row bands into a reused `ArrayBufferWriter`; the run aborts unless its bytes equal `JpegEncoder.Encode`'s. Recorded 2026-11-23 on the same Ryzen 7 5800X (Windows 11, .NET 10.0.15, AVX2), median of 15, machine shared with other jobs, MP/s: + +| config | buffered | streamed | streamed ÷ buffered time | +|---|---:|---:|---:| +| q50 4:2:0 | 636 | 604 | 1.05× | +| q75 4:2:0 | 587 | 588 | 1.00× | +| q85 4:2:0 | 543 | 543 | 1.00× | +| q90 4:2:0 | 505 | 500 | 1.01× | +| q95 4:2:0 | 442 | 441 | 1.00× | +| q90 4:4:4 | 312 | 311 | 1.00× | +| q95 4:4:4 | 275 | 276 | 1.00× | diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegEncoder.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegEncoder.cs index 374ee86..728819b 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/JpegEncoder.cs +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegEncoder.cs @@ -40,56 +40,26 @@ public static class JpegEncoder /// A dimension, channel count, or quality is out of range. public static byte[] Encode(ReadOnlySpan pixels, int width, int height, int channels, JpegEncodeOptions? options = null) { - if (width is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width), width, "Width must be 1..65535."); - if (height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(height), height, "Height must be 1..65535."); - if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels), channels, "Channels must be 1..4."); options ??= new JpegEncodeOptions(); - if (options.Quality is < 1 or > 100) throw new ArgumentOutOfRangeException(nameof(options), options.Quality, "Quality must be 1..100."); - if (options.RestartInterval is < 0 or > 65535) - throw new ArgumentOutOfRangeException(nameof(options), options.RestartInterval, "RestartInterval must be 0..65535."); - - var exif = ValidateExif(options.Exif); - var xmp = options.Xmp is { } xmpOptions ? BuildXmpPacket(xmpOptions) : default; - var icc = ValidateIcc(options.IccProfile); + var setup = Prepare(width, height, channels, options); var required = (long)width * height * channels; if (pixels.Length < required) throw new ArgumentException($"Pixel buffer too small: {pixels.Length} < {required} (width*height*channels).", nameof(pixels)); - var gray = channels <= 2; - var subsample = !gray && options.Subsampling switch - { - JpegSubsampling.Chroma444 => false, - JpegSubsampling.Chroma420 => true, - _ => options.Quality <= 90, - }; - - // libjpeg-style quality → quantiser scale percentage. - var q = options.Quality; - var scale = q < 50 ? 5000 / q : 200 - q * 2; - var lumaQuant = ScaleQuant(LumaQuant, scale); - var chromaQuant = ScaleQuant(ChromaQuant, scale); - - var frame = new Frame(width, height, gray, subsample) { RestartInterval = options.RestartInterval }; - frame.Components[0].Recip = Reciprocals(lumaQuant); - for (var c = 1; c < frame.Components.Length; c++) frame.Components[c].Recip = Reciprocals(chromaQuant); - + var frame = setup.Frame; var stored = options.Progressive || options.OptimizeHuffman; var w = new JpegBitWriter(EstimateCapacity(width, height, channels)); try { - WriteHeaders(ref w, exif.Span, xmp, icc.Span, lumaQuant, gray ? null : chromaQuant); if (!stored) { - WriteFrame(ref w, frame, progressive: false); - var (dcL, acL, dcC, acC) = (StdDcLuma, StdAcLuma, StdDcChroma, StdAcChroma); - WriteHuffmanTables(ref w, gray ? [(0, 0, dcL), (1, 0, acL)] : [(0, 0, dcL), (1, 0, acL), (0, 1, dcC), (1, 1, acC)]); - WriteRestartInterval(ref w, frame.RestartInterval); - WriteBaselineScanHeader(ref w, frame); - Transform(pixels, channels, frame, ref w, [dcL, dcC], [acL, acC]); + WriteBaselinePreamble(ref w, setup); + Transform(pixels, channels, frame, ref w, StdDcTables, StdAcTables); } else { + WriteHeaders(ref w, setup); foreach (var comp in frame.Components) comp.Coefficients = ArrayPool.Shared.Rent(checked(comp.BlocksW * comp.BlocksH * 64)); Transform(pixels, channels, frame, ref w, null, null); @@ -98,7 +68,7 @@ public static byte[] Encode(ReadOnlySpan pixels, int width, int height, in { WriteFrame(ref w, frame, progressive: true); WriteRestartInterval(ref w, frame.RestartInterval); - JpegProgressiveEncoder.Encode(ref w, frame, gray ? JpegProgressiveEncoder.GrayScript : JpegProgressiveEncoder.ColorScript); + JpegProgressiveEncoder.Encode(ref w, frame, frame.Components.Length == 1 ? JpegProgressiveEncoder.GrayScript : JpegProgressiveEncoder.ColorScript); } else { @@ -123,6 +93,73 @@ public static byte[] Encode(ReadOnlySpan pixels, int width, int height, in } } + /// What every coding mode needs before a sample is read: the checked options, metadata and tables. + internal sealed class Setup(Frame frame, ReadOnlyMemory exif, byte[]? xmp, ReadOnlyMemory icc, byte[] lumaQuant, byte[]? chromaQuant) + { + public readonly Frame Frame = frame; + public readonly ReadOnlyMemory Exif = exif, Icc = icc; + public readonly byte[]? Xmp = xmp; + public readonly byte[] LumaQuant = lumaQuant; + + /// Null for grey. + public readonly byte[]? ChromaQuant = chromaQuant; + } + + /// + /// Checks the geometry and (in this order: width, height, channels, quality, restart + /// interval, EXIF, XMP, ICC) and builds the frame and its quantisation tables. + /// + internal static Setup Prepare(int width, int height, int channels, JpegEncodeOptions options) + { + if (width is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width), width, "Width must be 1..65535."); + if (height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(height), height, "Height must be 1..65535."); + if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels), channels, "Channels must be 1..4."); + if (options.Quality is < 1 or > 100) throw new ArgumentOutOfRangeException(nameof(options), options.Quality, "Quality must be 1..100."); + if (options.RestartInterval is < 0 or > 65535) + throw new ArgumentOutOfRangeException(nameof(options), options.RestartInterval, "RestartInterval must be 0..65535."); + + var exif = ValidateExif(options.Exif); + var xmp = options.Xmp is { } xmpOptions ? BuildXmpPacket(xmpOptions) : null; + var icc = ValidateIcc(options.IccProfile); + + var gray = channels <= 2; + var subsample = !gray && options.Subsampling switch + { + JpegSubsampling.Chroma444 => false, + JpegSubsampling.Chroma420 => true, + _ => options.Quality <= 90, + }; + + // libjpeg-style quality → quantiser scale percentage. + var q = options.Quality; + var scale = q < 50 ? 5000 / q : 200 - q * 2; + var lumaQuant = ScaleQuant(LumaQuant, scale); + var chromaQuant = ScaleQuant(ChromaQuant, scale); + + var frame = new Frame(width, height, gray, subsample) { RestartInterval = options.RestartInterval }; + frame.Components[0].Recip = Reciprocals(lumaQuant); + for (var c = 1; c < frame.Components.Length; c++) frame.Components[c].Recip = Reciprocals(chromaQuant); + return new Setup(frame, exif, xmp, icc, lumaQuant, gray ? null : chromaQuant); + } + + /// + /// Everything a baseline file with the Annex K Huffman tables holds before its entropy-coded data: SOI, the + /// metadata segments, DQT, SOF0, DHT, DRI and SOS. + /// + internal static void WriteBaselinePreamble(ref JpegBitWriter w, Setup setup) + { + var frame = setup.Frame; + WriteHeaders(ref w, setup); + WriteFrame(ref w, frame, progressive: false); + var (dcL, acL, dcC, acC) = (StdDcLuma, StdAcLuma, StdDcChroma, StdAcChroma); + WriteHuffmanTables(ref w, frame.Components.Length == 1 ? [(0, 0, dcL), (1, 0, acL)] : [(0, 0, dcL), (1, 0, acL), (0, 1, dcC), (1, 1, acC)]); + WriteRestartInterval(ref w, frame.RestartInterval); + WriteBaselineScanHeader(ref w, frame); + } + + private static void WriteHeaders(ref JpegBitWriter w, Setup setup) => + WriteHeaders(ref w, setup.Exif.Span, setup.Xmp, setup.Icc.Span, setup.LumaQuant, setup.ChromaQuant); + // -------------------------------------------------------------- frame geometry internal sealed class Component(byte id, int h, int v, int tableId) @@ -181,6 +218,9 @@ public Frame(int width, int height, bool gray, bool subsample) private static readonly JpegHuffmanEncodeTable StdDcChroma = JpegHuffmanEncodeTable.FromSpec(DcChromaBits, DcChromaValues); private static readonly JpegHuffmanEncodeTable StdAcChroma = JpegHuffmanEncodeTable.FromSpec(AcChromaBits, AcChromaValues); + /// The Annex K tables by (declared after the tables they hold). + internal static readonly JpegHuffmanEncodeTable[] StdDcTables = [StdDcLuma, StdDcChroma], StdAcTables = [StdAcLuma, StdAcChroma]; + private static byte[] ScaleQuant(ReadOnlySpan basis, int scale) { var t = new byte[64]; @@ -214,195 +254,235 @@ private static int EstimateCapacity(int width, int height, int channels) => /// /// Runs colour conversion and the forward DCT over the whole image, one MCU row at a time - /// in chunks of columns. With Huffman tables given, every block is - /// entropy coded straight after its transform; otherwise the quantised coefficients are - /// stored in each component's grid. + /// (). With Huffman tables given, every block is entropy coded straight + /// after its transform; otherwise the quantised coefficients are stored in each component's grid. /// - [MethodImpl(MethodImplOptions.AggressiveOptimization)] private static void Transform(ReadOnlySpan pixels, int channels, Frame f, ref JpegBitWriter w, JpegHuffmanEncodeTable[]? dcTables, JpegHuffmanEncodeTable[]? acTables) { - var comps = f.Components; - var gray = comps.Length == 1; - var subsample = f.HMax == 2; - var rows = 8 * f.VMax; - var mcuWidth = 8 * f.HMax; - var chunkMcus = ChunkWidth / mcuWidth; - const int stride = ChunkWidth; - const int halfStride = ChunkWidth / 2; + using var rows = new McuRowEncoder(f, channels, dcTables, acTables); var rowBytes = f.Width * channels; + for (var my = 0; my < f.McusY; my++) + rows.Encode(pixels[(my * rows.Rows * rowBytes)..], rowBytes, my, ref w); + } - var planeLength = rows * stride; - var y = ArrayPool.Shared.Rent(planeLength); - var fullChroma = !gray && !subsample; - float[] cb = fullChroma ? ArrayPool.Shared.Rent(planeLength) : []; - float[] cr = fullChroma ? ArrayPool.Shared.Rent(planeLength) : []; - float[] cb2 = subsample ? ArrayPool.Shared.Rent(8 * halfStride) : []; - float[] cr2 = subsample ? ArrayPool.Shared.Rent(8 * halfStride) : []; - Span scratch = stackalloc short[64]; - Span pred = stackalloc int[3]; - pred.Clear(); - var restart = f.RestartInterval; - var mcusDone = 0; // MCUs entropy coded so far, for the restart intervals - var restartIndex = 0; - var store = dcTables is null; - var dcCodes = new uint[comps.Length][]; - var acCodes = new uint[comps.Length][]; - if (!store) + /// + /// The transform pipeline for one MCU row at a time (8 image rows, or 16 for 4:2:0), in chunks of + /// columns so the float planes stay cache-resident. It holds the state one MCU + /// row hands to the next (DC predictors, restart count), so the buffered encoder and the streaming + /// session code the same bytes from the same rows. + /// + internal sealed class McuRowEncoder : IDisposable + { + private readonly Frame _f; + private readonly int _channels; + private readonly float[] _y, _cb, _cr, _cb2, _cr2; + private readonly int[] _pred = new int[3]; + private readonly uint[][] _dcCodes, _acCodes; + private readonly bool _store; + private int _mcusDone; // MCUs entropy coded so far, for the restart intervals + private int _restartIndex; + private bool _disposed; + + /// The frame (its components' set; with no tables, their + /// allocated). + /// Interleaved samples per pixel of the rows given to . + /// DC tables by ; null to store coefficients. + /// AC tables by ; null to store coefficients. + public McuRowEncoder(Frame f, int channels, JpegHuffmanEncodeTable[]? dcTables, JpegHuffmanEncodeTable[]? acTables) { - for (var c = 0; c < comps.Length; c++) + _f = f; + _channels = channels; + var comps = f.Components; + var gray = comps.Length == 1; + var subsample = f.HMax == 2; + var planeLength = Rows * ChunkWidth; + var fullChroma = !gray && !subsample; + _y = ArrayPool.Shared.Rent(planeLength); + _cb = fullChroma ? ArrayPool.Shared.Rent(planeLength) : []; + _cr = fullChroma ? ArrayPool.Shared.Rent(planeLength) : []; + _cb2 = subsample ? ArrayPool.Shared.Rent(8 * (ChunkWidth / 2)) : []; + _cr2 = subsample ? ArrayPool.Shared.Rent(8 * (ChunkWidth / 2)) : []; + _store = dcTables is null; + _dcCodes = new uint[comps.Length][]; + _acCodes = new uint[comps.Length][]; + if (!_store) { - dcCodes[c] = dcTables![comps[c].TableId].Packed; - acCodes[c] = acTables![comps[c].TableId].AcCombined; + for (var c = 0; c < comps.Length; c++) + { + _dcCodes[c] = dcTables![comps[c].TableId].Packed; + _acCodes[c] = acTables![comps[c].TableId].AcCombined; + } } } - try + /// Image rows per MCU row: 8, or 16 for 4:2:0. + public int Rows => 8 * _f.VMax; + + /// + /// Transforms (and codes, or stores) MCU row . Row r of , + /// bytes apart, is image row my × Rows + r; the band holds every image row + /// of the MCU row (fewer than only in the last, whose missing rows replicate the image's last). + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + public void Encode(ReadOnlySpan band, int bandStride, int my, ref JpegBitWriter w) { - for (var my = 0; my < f.McusY; my++) + var f = _f; + var comps = f.Components; + var gray = comps.Length == 1; + var subsample = f.HMax == 2; + var rows = 8 * f.VMax; + var mcuWidth = 8 * f.HMax; + var chunkMcus = ChunkWidth / mcuWidth; + const int stride = ChunkWidth; + const int halfStride = ChunkWidth / 2; + var channels = _channels; + var (y, cb, cr, cb2, cr2) = (_y, _cb, _cr, _cb2, _cr2); + var lastRow = Math.Min(rows, f.Height - my * rows) - 1; // the band's last row, ≥ 0 + Span scratch = stackalloc short[64]; + Span pred = _pred; + var restart = f.RestartInterval; + var dcCodes = _dcCodes; + var acCodes = _acCodes; + + for (var cx = 0; cx < f.McusX; cx += chunkMcus) { - for (var cx = 0; cx < f.McusX; cx += chunkMcus) + var mcus = Math.Min(chunkMcus, f.McusX - cx); + var x0 = cx * mcuWidth; + var width = mcus * mcuWidth; + var valid = Math.Min(width, f.Width - x0); // ≥ 1: McusX = ceil(Width / mcuWidth) + + // Level-shifted planes for this chunk, rows past the bottom replicating the last + // image row and columns past the right edge the last column (the last chroma + // column for 4:2:0). + if (subsample) { - var mcus = Math.Min(chunkMcus, f.McusX - cx); - var x0 = cx * mcuWidth; - var width = mcus * mcuWidth; - var valid = Math.Min(width, f.Width - x0); // ≥ 1: McusX = ceil(Width / mcuWidth) - - // Level-shifted planes for this chunk, rows past the bottom replicating the last - // image row and columns past the right edge the last column (the last chroma - // column for 4:2:0). - if (subsample) + var cValid = (valid + 1) / 2; + for (var r = 0; r < 8; r++) { - var cValid = (valid + 1) / 2; - for (var r = 0; r < 8; r++) + var row0 = Math.Min(2 * r, lastRow); + var row1 = Math.Min(2 * r + 1, lastRow); + var ys0 = y.AsSpan(2 * r * stride, width); + var ys1 = y.AsSpan((2 * r + 1) * stride, width); + var cbs = cb2.AsSpan(r * halfStride, width / 2); + var crs = cr2.AsSpan(r * halfStride, width / 2); + JpegEncoderKernels.ConvertRowPair420( + band.Slice(row0 * bandStride + x0 * channels, valid * channels), + band.Slice(row1 * bandStride + x0 * channels, valid * channels), + channels, valid, ys0, ys1, cbs, crs); + if (valid < width) { - var row0 = Math.Min(my * 16 + 2 * r, f.Height - 1); - var row1 = Math.Min(my * 16 + 2 * r + 1, f.Height - 1); - var ys0 = y.AsSpan(2 * r * stride, width); - var ys1 = y.AsSpan((2 * r + 1) * stride, width); - var cbs = cb2.AsSpan(r * halfStride, width / 2); - var crs = cr2.AsSpan(r * halfStride, width / 2); - JpegEncoderKernels.ConvertRowPair420( - pixels.Slice(row0 * rowBytes + x0 * channels, valid * channels), - pixels.Slice(row1 * rowBytes + x0 * channels, valid * channels), - channels, valid, ys0, ys1, cbs, crs); - if (valid < width) - { - ys0[valid..].Fill(ys0[valid - 1]); - ys1[valid..].Fill(ys1[valid - 1]); - cbs[cValid..].Fill(cbs[cValid - 1]); - crs[cValid..].Fill(crs[cValid - 1]); - } + ys0[valid..].Fill(ys0[valid - 1]); + ys1[valid..].Fill(ys1[valid - 1]); + cbs[cValid..].Fill(cbs[cValid - 1]); + crs[cValid..].Fill(crs[cValid - 1]); } } + } - var prevSrc = -1; - for (var r = 0; !subsample && r < rows; r++) + var prevSrc = -1; + for (var r = 0; !subsample && r < rows; r++) + { + var srcRow = Math.Min(r, lastRow); + var o = r * stride; + if (srcRow == prevSrc) { - var srcRow = Math.Min(my * rows + r, f.Height - 1); - var o = r * stride; - if (srcRow == prevSrc) + y.AsSpan(o - stride, width).CopyTo(y.AsSpan(o, width)); + if (!gray) { - y.AsSpan(o - stride, width).CopyTo(y.AsSpan(o, width)); - if (!gray) - { - cb.AsSpan(o - stride, width).CopyTo(cb.AsSpan(o, width)); - cr.AsSpan(o - stride, width).CopyTo(cr.AsSpan(o, width)); - } - - continue; + cb.AsSpan(o - stride, width).CopyTo(cb.AsSpan(o, width)); + cr.AsSpan(o - stride, width).CopyTo(cr.AsSpan(o, width)); } - prevSrc = srcRow; - var src = pixels.Slice(srcRow * rowBytes + x0 * channels, valid * channels); - var ys = y.AsSpan(o, width); - Span cbs = gray ? [] : cb.AsSpan(o, width); - Span crs = gray ? [] : cr.AsSpan(o, width); - JpegEncoderKernels.ConvertRow(src, channels, valid, ys, cbs, crs); - if (valid < width) - { - ys[valid..].Fill(ys[valid - 1]); - if (!gray) - { - cbs[valid..].Fill(cbs[valid - 1]); - crs[valid..].Fill(crs[valid - 1]); - } - } + continue; } - - if (!store) + prevSrc = srcRow; + var src = band.Slice(srcRow * bandStride + x0 * channels, valid * channels); + var ys = y.AsSpan(o, width); + Span cbs = gray ? [] : cb.AsSpan(o, width); + Span crs = gray ? [] : cr.AsSpan(o, width); + JpegEncoderKernels.ConvertRow(src, channels, valid, ys, cbs, crs); + if (valid < width) { - var c1 = subsample ? cb2 : cb; - var c2 = subsample ? cr2 : cr; - var cStride = subsample ? halfStride : stride; - if (restart == 0) + ys[valid..].Fill(ys[valid - 1]); + if (!gray) { - EncodeChunk(ref w, comps, 0, mcus, y, c1, c2, stride, cStride, pred, dcCodes, acCodes, scratch); - continue; + cbs[valid..].Fill(cbs[valid - 1]); + crs[valid..].Fill(crs[valid - 1]); } + } + } - // Restart intervals: the chunk is coded in runs that end on an interval boundary, so - // the per-MCU loop stays free of the check. A marker goes before an interval's first - // MCU, never after the image's last (T.81 B.2.4.4, F.1.2.3). - for (var s = 0; s < mcus;) - { - if (mcusDone > 0 && mcusDone % restart == 0) - { - w.WriteRestart(restartIndex++); - pred.Clear(); - } + if (!_store) + { + var c1 = subsample ? cb2 : cb; + var c2 = subsample ? cr2 : cr; + var cStride = subsample ? halfStride : stride; + if (restart == 0) + { + EncodeChunk(ref w, comps, 0, mcus, y, c1, c2, stride, cStride, pred, dcCodes, acCodes, scratch); + continue; + } - var run = Math.Min(mcus - s, restart - mcusDone % restart); - EncodeChunk(ref w, comps, s, s + run, y, c1, c2, stride, cStride, pred, dcCodes, acCodes, scratch); - s += run; - mcusDone += run; + // Restart intervals: the chunk is coded in runs that end on an interval boundary, so + // the per-MCU loop stays free of the check. A marker goes before an interval's first + // MCU, never after the image's last (T.81 B.2.4.4, F.1.2.3). + for (var s = 0; s < mcus;) + { + if (_mcusDone > 0 && _mcusDone % restart == 0) + { + w.WriteRestart(_restartIndex++); + pred.Clear(); } - continue; + var run = Math.Min(mcus - s, restart - _mcusDone % restart); + EncodeChunk(ref w, comps, s, s + run, y, c1, c2, stride, cStride, pred, dcCodes, acCodes, scratch); + s += run; + _mcusDone += run; } - for (var mx = 0; mx < mcus; mx++) + continue; + } + + for (var mx = 0; mx < mcus; mx++) + { + for (var c = 0; c < comps.Length; c++) { - for (var c = 0; c < comps.Length; c++) + var comp = comps[c]; + float[] plane; + int planeStride; + if (c == 0) { plane = y; planeStride = stride; } + else if (subsample) { plane = c == 1 ? cb2 : cr2; planeStride = halfStride; } + else { plane = c == 1 ? cb : cr; planeStride = stride; } + + for (var v = 0; v < comp.V; v++) { - var comp = comps[c]; - float[] plane; - int planeStride; - if (c == 0) { plane = y; planeStride = stride; } - else if (subsample) { plane = c == 1 ? cb2 : cr2; planeStride = halfStride; } - else { plane = c == 1 ? cb : cr; planeStride = stride; } - - for (var v = 0; v < comp.V; v++) + for (var h = 0; h < comp.H; h++) { - for (var h = 0; h < comp.H; h++) - { - var local = mx * comp.H + h; - JpegEncoderKernels.ForwardDct(plane.AsSpan(v * 8 * planeStride + local * 8), planeStride, comp.Recip, - comp.Block(my * comp.V + v, cx * comp.H + local)); - } + var local = mx * comp.H + h; + JpegEncoderKernels.ForwardDct(plane.AsSpan(v * 8 * planeStride + local * 8), planeStride, comp.Recip, + comp.Block(my * comp.V + v, cx * comp.H + local)); } } } } } } - finally - { - ArrayPool.Shared.Return(y); - if (fullChroma) - { - ArrayPool.Shared.Return(cb); - ArrayPool.Shared.Return(cr); - } - if (subsample) - { - ArrayPool.Shared.Return(cb2); - ArrayPool.Shared.Return(cr2); - } + /// Returns the float planes to the pool. + public void Dispose() + { + if (_disposed) return; + _disposed = true; + ArrayPool.Shared.Return(_y); + if (_cb.Length > 0) ArrayPool.Shared.Return(_cb); + if (_cr.Length > 0) ArrayPool.Shared.Return(_cr); + if (_cb2.Length > 0) ArrayPool.Shared.Return(_cb2); + if (_cr2.Length > 0) ArrayPool.Shared.Return(_cr2); } } + // -------------------------------------------------------------- sequential entropy coding /// diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegImageEncoder.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegImageEncoder.cs index 48f3a62..a70b56b 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/JpegImageEncoder.cs +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegImageEncoder.cs @@ -12,7 +12,11 @@ namespace Sdcb.SimdCodecs.Jpeg; /// byte; BGR(A) is reordered by the session. /// /// The output is exactly what writes for the converted pixels and the -/// given (a still format: one frame). A frame's sets +/// given (a still format: one frame). Baseline encoding with the standard tables streams +/// ( true): the headers reach the writer at AddFrame and each MCU row +/// (8 rows, 16 for 4:2:0) as soon as its last row is written, so the session holds one MCU row, not the image. +/// and need every coefficient +/// first; their session collects the image and encodes it at Commit (IsStreaming false). A frame's sets /// and , overriding the options' own. A block /// that cannot be written is dropped, not an error: an Exif blob that is not a TIFF structure or is over /// , an ICC profile over . @@ -41,13 +45,17 @@ public sealed class JpegImageEncoder : IImageEncoder /// /// is a (null means the defaults; any other type /// throws ). - public static IImageEncoderSession Create(IBufferWriter output, EncodeOptions? options = null) => - new Session(output, options switch + public static IImageEncoderSession Create(IBufferWriter output, EncodeOptions? options = null) + { + var o = options switch { null => new JpegEncodeOptions(), - JpegEncodeOptions o => o, + JpegEncodeOptions jpeg => jpeg, _ => throw new ArgumentException($"JPEG encoding takes JpegEncodeOptions, not {options.GetType().Name}.", nameof(options)), - }); + }; + // Optimised Huffman tables and progressive scans need every coefficient before the first scan is written. + return o.Progressive || o.OptimizeHuffman ? new Session(output, o) : new StreamingSession(output, o); + } private static PixelFormat Native(PixelFormat f) => f.Layout switch { @@ -68,24 +76,161 @@ protected override void Encode(IReadOnlyList frames, Cancellation var frame = frames[0]; var native = Native(frame.Format); var pixels = frame.PixelsAs(native); - var channels = native.Layout switch { ChannelLayout.Rgba => 4, ChannelLayout.Rgb => 3, _ => 1 }; - WriteOutput(JpegEncoder.Encode(pixels, frame.Width, frame.Height, channels, WithFrame(options, frame))); + var channels = Channels(native); + WriteOutput(JpegEncoder.Encode(pixels, frame.Width, frame.Height, channels, WithMetadata(options, frame.Metadata))); + } + } + + private static int Channels(PixelFormat native) => native.Layout switch { ChannelLayout.Rgba => 4, ChannelLayout.Rgb => 3, _ => 1 }; + + private static JpegEncodeOptions WithMetadata(JpegEncodeOptions options, ImageMetadata? metadata) + { + var o = options; + if (metadata is { } m) + { + if (IsTiffBlob(m.Exif.Span) && m.Exif.Length <= JpegEncodeOptions.MaxExifBytes) + o = o with { Exif = m.Exif }; + if (!m.Icc.IsEmpty && m.Icc.Length <= JpegEncodeOptions.MaxIccProfileBytes) + o = o with { IccProfile = m.Icc }; + } + return o; + } + + private static bool IsTiffBlob(ReadOnlySpan b) => + b.Length >= 8 && (b[..4].SequenceEqual("II*\0"u8) || b[..4].SequenceEqual("MM\0*"u8)); + + /// + /// Baseline with the Annex K tables: the headers go out at AddFrame, then each MCU row (8 image rows, 16 for + /// 4:2:0) is transformed, coded and handed to the writer as soon as its last row arrives, so memory is one MCU row of + /// pixels and of output. It is the buffered encoder fed a row at a time: the same bytes for the same pixels, however + /// the rows are split across WriteRows calls. + /// + private sealed class StreamingSession(IBufferWriter output, JpegEncodeOptions options) : StreamingEncoderSession(output) + { + private JpegBitWriter _w; + private JpegEncoder.McuRowEncoder? _rows; + private byte[]? _band; // rows of the MCU row being collected, in the native format, tightly packed + private PixelFormat _format, _native; + private int _width, _height, _rowBytes, _mcuRows, _filled, _my; + private bool _faulted; + + public override int MaxFrames => 1; + + protected override int MaxDimension => 65535; + + protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) + { + var native = Native(format); + var channels = Channels(native); + var setup = JpegEncoder.Prepare(width, height, channels, WithMetadata(options, metadata)); + ThrowIfFaulted(); + (_format, _native, _width, _height) = (format, native, width, height); + _rowBytes = width * channels; + _w = new JpegBitWriter(4096); + _faulted = true; // until the headers are out: a retried AddFrame must not write them twice + JpegEncoder.WriteBaselinePreamble(ref _w, setup); + Flush(); + _faulted = false; + _rows = new JpegEncoder.McuRowEncoder(setup.Frame, channels, JpegEncoder.StdDcTables, JpegEncoder.StdAcTables); + _mcuRows = _rows.Rows; + } + + protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) + { + // A call that stops part way (cancelled, or the writer threw) has coded rows the session does not count as + // written (or part of the headers or trailer is out); going on would write a corrupt file, so the session refuses. + ThrowIfFaulted(); + _faulted = true; + EncodeRowsCore(rows, rowCount, stride, cancellationToken); + _faulted = false; } - private static JpegEncodeOptions WithFrame(JpegEncodeOptions options, BufferedFrame frame) + private void EncodeRowsCore(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) { - var o = options; - if (frame.Metadata is { } m) + while (rowCount > 0) { - if (IsTiffBlob(m.Exif.Span) && m.Exif.Length <= JpegEncodeOptions.MaxExifBytes) - o = o with { Exif = m.Exif }; - if (!m.Icc.IsEmpty && m.Icc.Length <= JpegEncodeOptions.MaxIccProfileBytes) - o = o with { IccProfile = m.Icc }; + // Rows the current MCU row still needs: all of them, fewer only in the image's last MCU row. + var need = Math.Min(_mcuRows, _height - _my * _mcuRows); + if (_filled == 0 && rowCount >= need && _format == _native) + { + // A whole MCU row in the native format: coded straight from the caller's rows. + EncodeMcuRow(rows, stride, cancellationToken); + } + else + { + var take = Math.Min(rowCount, need - _filled); + _band ??= ArrayPool.Shared.Rent(_mcuRows * _rowBytes); + PixelConverter.Convert(rows, stride, _format, _band.AsSpan(_filled * _rowBytes), _rowBytes, _native, _width, take); + _filled += take; + rowCount -= take; + if (rowCount > 0) + rows = rows[(take * stride)..]; + if (_filled == need) + { + _filled = 0; + EncodeMcuRow(_band, _rowBytes, cancellationToken); + } + continue; + } + + rowCount -= need; + if (rowCount > 0) + rows = rows[(need * stride)..]; } - return o; } - private static bool IsTiffBlob(ReadOnlySpan b) => - b.Length >= 8 && (b[..4].SequenceEqual("II*\0"u8) || b[..4].SequenceEqual("MM\0*"u8)); + private void EncodeMcuRow(ReadOnlySpan band, int stride, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + _rows!.Encode(band, stride, _my++, ref _w); + Flush(); + } + + protected override void EndFrame(CancellationToken cancellationToken) + { + _faulted = true; // cleared once EOI is out, so a writer failure here fails Commit too + _w.FlushBits(); + _w.WriteByte(0xFF); + _w.WriteByte(0xD9); + Flush(); + _faulted = false; + Release(); + } + + protected override void Finish(CancellationToken cancellationToken) => ThrowIfFaulted(); + + private void ThrowIfFaulted() + { + if (_faulted) + throw new InvalidOperationException("An earlier call failed part way through writing the file; the session cannot continue."); + } + + /// + /// Hands the finished bytes to the output and starts the buffer over. Every coded MCU ends with the stuffing pass + /// () and a marker or header ends on a byte, so [0, Position) is final; + /// the under-8 pending bits stay in the accumulator and the next store rewrites them at the new position. + /// + private void Flush() + { + WriteOutput(_w.Buffer.AsSpan(0, _w.Position)); + _w.Position = 0; + _w.Mark = 0; + } + + private void Release() + { + _rows?.Dispose(); + _rows = null; + if (_band is not null) ArrayPool.Shared.Return(_band); + _band = null; + if (_w.Buffer is { Length: > 0 }) ArrayPool.Shared.Return(_w.Buffer); + _w.Buffer = []; + } + + protected override void Dispose(bool disposing) + { + if (disposing) Release(); + } } } diff --git a/src/Sdcb.SimdCodecs.Jpeg/README.md b/src/Sdcb.SimdCodecs.Jpeg/README.md index 0c15dad..389537d 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/README.md +++ b/src/Sdcb.SimdCodecs.Jpeg/README.md @@ -32,6 +32,20 @@ byte[] jpeg = JpegEncoder.Encode(rgba, width, height, quality: 85); `JpegEncodeOptions` selects chroma subsampling, optimised Huffman tables, progressive mode, a restart interval (`RestartInterval`, in MCUs: DRI plus RST0..RST7 markers in every scan, decoded pixels unchanged), and an optional Exif blob. +## Streaming encode + +`JpegImageEncoder.Create` returns a streaming session for baseline encoding with the standard tables (every option except `OptimizeHuffman` and `Progressive`): the headers reach the writer at `AddFrame`, and each MCU row (8 image rows, 16 for 4:2:0) is coded and handed over as soon as its last row is written. The session holds one MCU row of pixels and of output, so a large image can be encoded from a row source straight to a file. Its bytes are exactly `JpegEncoder.Encode`'s for the same pixels and options, however the rows are split across `WriteRows` calls. + +```csharp +using var session = JpegImageEncoder.Create(writer, new JpegEncodeOptions { Quality = 85 }); +var frame = session.AddFrame(width, height, PixelFormat.Rgb24); +while (source.ReadBand(band, out int rows)) // any band height + frame.WriteRows(band, rows); +session.Commit(); +``` + +`OptimizeHuffman` and `Progressive` need every coefficient before the first scan is written; with either set the session collects the image and encodes it at `Commit` (`IsStreaming` is false), with the same output as before. + ## JPEG inside another container A container that stores JPEG streams can carry their tables apart from them and say itself what the components mean, as TIFF does (JPEGTables and PhotometricInterpretation, TIFF Technical Note 2). `JpegDecodeOptions` takes both: diff --git a/tests/Sdcb.SimdCodecs.Tests/JpegStreamingEncodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/JpegStreamingEncodeTests.cs new file mode 100644 index 0000000..0abf3fa --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/JpegStreamingEncodeTests.cs @@ -0,0 +1,387 @@ +using System.Buffers; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Jpeg; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// 's streaming session (baseline, Annex K tables): its bytes equal the buffered encoder's +/// for the same pixels and options however the rows are split, they reach the writer before Commit, and memory +/// stays one MCU row. Optimised and progressive encoding fall back to the buffered session. +/// +public sealed class JpegStreamingEncodeTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// A smooth photo-like field (gradients, a few edges) with noise, so every coefficient band gets used. + private static void FillPhoto(Span rows, int width, int y0, int rowCount, int bpp, int seed) + { + var random = new Random(seed * 7919 + y0); + for (var r = 0; r < rowCount; r++) + { + var y = y0 + r; + for (var x = 0; x < width; x++) + { + var o = (r * width + x) * bpp; + var edge = ((x / 37) + (y / 23)) % 3 == 0 ? 60 : 0; + for (var c = 0; c < bpp; c++) + { + var v = (x * (c + 1) * 3 + y * (5 - c) + edge) % 256 + random.Next(-12, 13); + rows[o + c] = (byte)Math.Clamp(v, 0, 255); + } + } + } + } + + private static byte[] Photo(int width, int height, int bpp, int seed) + { + var data = new byte[width * height * bpp]; + FillPhoto(data, width, 0, height, bpp, seed); + return data; + } + + private static byte[] Buffered(byte[] pixels, int width, int height, PixelFormat format, JpegEncodeOptions options) + { + var native = JpegImageEncoder.GetClosestInputFormat(format); + var converted = format == native ? pixels : PixelConverter.ToPacked(pixels, 0, format, native, width, height); + return JpegEncoder.Encode(converted, width, height, native.Channels, options); + } + + /// Streams in bands of the given sizes (cycled), at a padded stride. + private static byte[] Streamed(byte[] pixels, int width, int height, PixelFormat format, JpegEncodeOptions? options, + int[] bands, int pad = 0, ImageMetadata? metadata = null) + { + var rowBytes = width * format.BytesPerPixel; + var stride = rowBytes + pad; + var padded = new byte[stride * height]; + for (var y = 0; y < height; y++) + pixels.AsSpan(y * rowBytes, rowBytes).CopyTo(padded.AsSpan(y * stride)); + var output = new ArrayBufferWriter(); + using var session = JpegImageEncoder.Create(output, options); + session.IsStreaming.ShouldBe(options is not { Progressive: true } and not { OptimizeHuffman: true }); + var frame = session.AddFrame(width, height, format, null, metadata); + for (int y = 0, i = 0; y < height; i++) + { + var n = Math.Min(bands[i % bands.Length], height - y); + frame.WriteRows(padded.AsSpan(y * stride), n, stride, Ct); + y += n; + } + session.Commit(Ct); + return output.WrittenSpan.ToArray(); + } + + private static readonly int[][] Splits = [[1], [3, 7, 1, 16], [8], [16], [5, 100], [int.MaxValue]]; + + public static TheoryData Sizes => new() { { 1, 1 }, { 17, 9 }, { 33, 17 }, { 40, 31 }, { 16, 16 }, { 2049, 19 }, { 4113, 33 } }; + + [Theory] + [MemberData(nameof(Sizes))] + public void Bytes_equal_the_buffered_encoder_for_every_split_subsampling_and_quality(int width, int height) + { + foreach (var subsampling in new[] { JpegSubsampling.Chroma420, JpegSubsampling.Chroma444, JpegSubsampling.Auto }) + foreach (var quality in new[] { 1, 50, 91, 100 }) + { + var options = new JpegEncodeOptions { Quality = quality, Subsampling = subsampling }; + var pixels = Photo(width, height, 3, quality); + var expected = Buffered(pixels, width, height, PixelFormat.Rgb24, options); + foreach (var split in Splits) + { + Streamed(pixels, width, height, PixelFormat.Rgb24, options, split, pad: split[0] % 5) + .ShouldBe(expected, $"{width}x{height} {subsampling} q{quality} split [{string.Join(',', split)}]"); + } + } + } + + [Fact] + public void Bytes_equal_the_buffered_encoder_for_every_input_format() + { + const int width = 37, height = 21; + foreach (var format in PixelFormat.All) + foreach (var subsampling in new[] { JpegSubsampling.Chroma420, JpegSubsampling.Chroma444 }) + { + var options = new JpegEncodeOptions { Quality = 80, Subsampling = subsampling }; + var pixels = new byte[width * height * format.BytesPerPixel]; + new Random(format.GetHashCode()).NextBytes(pixels); + var expected = Buffered(pixels, width, height, format, options); + foreach (var split in new[] { [1], [5, 16, 2], new[] { height } }) + Streamed(pixels, width, height, format, options, split, pad: 3).ShouldBe(expected, $"{format} {subsampling}"); + } + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(5)] + [InlineData(130)] + public void Restart_intervals_stream_to_the_same_bytes(int interval) + { + foreach (var (width, height) in new[] { (17, 9), (300, 41), (2100, 20) }) + foreach (var subsampling in new[] { JpegSubsampling.Chroma420, JpegSubsampling.Chroma444 }) + { + var options = new JpegEncodeOptions { Quality = 85, Subsampling = subsampling, RestartInterval = interval }; + var pixels = Photo(width, height, 3, interval); + var expected = Buffered(pixels, width, height, PixelFormat.Rgb24, options); + foreach (var split in new[] { [1], [7, 9], new[] { height } }) + Streamed(pixels, width, height, PixelFormat.Rgb24, options, split).ShouldBe(expected, $"{width}x{height} {subsampling} Ri {interval}"); + } + } + + [Fact] + public void Grey_input_streams_to_the_same_bytes() + { + foreach (var (width, height) in new[] { (1, 1), (17, 9), (100, 77) }) + { + var options = new JpegEncodeOptions { Quality = 70, RestartInterval = 4 }; + var pixels = Photo(width, height, 1, 3); + var expected = Buffered(pixels, width, height, PixelFormat.Gray8, options); + foreach (var split in Splits) + Streamed(pixels, width, height, PixelFormat.Gray8, options, split).ShouldBe(expected, $"{width}x{height}"); + } + } + + [Fact] + public void Metadata_from_options_and_from_the_frame_stream_to_the_same_bytes() + { + const int width = 45, height = 30; + byte[] exif = [(byte)'M', (byte)'M', 0, (byte)'*', 0, 0, 0, 8, 0, 0, 0, 0]; + var icc = new byte[JpegEncodeOptions.MaxIccChunkBytes + 1000]; // two APP2 chunks + new Random(9).NextBytes(icc); + var pixels = Photo(width, height, 4, 1); + var options = new JpegEncodeOptions + { + Quality = 88, + Exif = exif, + IccProfile = icc, + Xmp = new JpegXmp { Description = "streamed" }, + }; + var expected = Buffered(pixels, width, height, PixelFormat.Rgba32, options); + Streamed(pixels, width, height, PixelFormat.Rgba32, options, [4]).ShouldBe(expected); + + // The frame's metadata overrides the options', as in the buffered session. + var frameIcc = new byte[500]; + new Random(10).NextBytes(frameIcc); + var metadata = new ImageMetadata { Exif = exif, Icc = frameIcc }; + var bare = new JpegEncodeOptions { Quality = 88 }; + Streamed(pixels, width, height, PixelFormat.Rgba32, bare, [3], metadata: metadata) + .ShouldBe(Buffered(pixels, width, height, PixelFormat.Rgba32, bare with { Exif = exif, IccProfile = frameIcc })); + } + + [Fact] + public void Optimised_and_progressive_fall_back_to_the_buffered_session_with_unchanged_bytes() + { + const int width = 50, height = 35; + var pixels = Photo(width, height, 3, 4); + foreach (var options in new[] + { + new JpegEncodeOptions { OptimizeHuffman = true }, + new JpegEncodeOptions { Progressive = true }, + new JpegEncodeOptions { Progressive = true, OptimizeHuffman = true, RestartInterval = 2 }, + }) + { + using (var session = JpegImageEncoder.Create(new ArrayBufferWriter(), options)) + session.IsStreaming.ShouldBeFalse(); + Streamed(pixels, width, height, PixelFormat.Rgb24, options, [3, 8]) + .ShouldBe(Buffered(pixels, width, height, PixelFormat.Rgb24, options)); + } + using (var session = JpegImageEncoder.Create(new ArrayBufferWriter())) + session.IsStreaming.ShouldBeTrue(); + } + + [Fact] + public void Bytes_reach_the_writer_before_commit() + { + const int width = 64, height = 64; + var pixels = Photo(width, height, 3, 5); + var file = StreamingAssert.EncoderEmitsBeforeCommit(o => JpegImageEncoder.Create(o), pixels, width, height, PixelFormat.Rgb24); + file.ShouldBe(Buffered(pixels, width, height, PixelFormat.Rgb24, new JpegEncodeOptions())); + } + + [Fact] + public void Each_mcu_row_is_written_as_soon_as_its_last_row_arrives() + { + const int width = 40, height = 40; + var pixels = Photo(width, height, 3, 6); + var output = new ArrayBufferWriter(); + using var session = JpegImageEncoder.Create(output, new JpegEncodeOptions { Subsampling = JpegSubsampling.Chroma420 }); + var frame = session.AddFrame(width, height, PixelFormat.Rgb24); + var headers = output.WrittenCount; + headers.ShouldBeGreaterThan(0, "headers at AddFrame"); + var rowBytes = width * 3; + frame.WriteRows(pixels, 15, 0, Ct); + output.WrittenCount.ShouldBe(headers, "15 of 16 rows: the MCU row is not complete"); + frame.WriteRows(pixels.AsSpan(15 * rowBytes), 1, 0, Ct); + output.WrittenCount.ShouldBeGreaterThan(headers, "the 16th row completes the first MCU row"); + frame.WriteRows(pixels.AsSpan(16 * rowBytes), height - 16, 0, Ct); + session.Commit(Ct); + output.WrittenSpan.ToArray().ShouldBe(Buffered(pixels, width, height, PixelFormat.Rgb24, new JpegEncodeOptions { Subsampling = JpegSubsampling.Chroma420 })); + } + + [Fact] + public void Invalid_options_throw_at_add_frame() + { + using var session = JpegImageEncoder.Create(new ArrayBufferWriter(), new JpegEncodeOptions { Quality = 0 }); + Should.Throw(() => session.AddFrame(8, 8, PixelFormat.Rgb24)); + } + + [Fact] + public void Cancellation_stops_the_session_before_the_next_mcu_row() + { + // The token is cancelled while one WriteRows call is coding: once the first MCU row reaches the writer. + const int width = 32, height = 32; + var pixels = Photo(width, height, 3, 7); + using var cts = new CancellationTokenSource(); + var output = new CancellingWriter(cts); + using var session = JpegImageEncoder.Create(output, new JpegEncodeOptions { Subsampling = JpegSubsampling.Chroma444 }); + var frame = session.AddFrame(width, height, PixelFormat.Rgb24); + output.Armed = true; + Should.Throw(() => frame.WriteRows(pixels, height, 0, cts.Token)); + output.Advances.ShouldBe(1, "one MCU row was coded, then the session stopped"); + frame.RowsWritten.ShouldBe(0); + Should.Throw(() => frame.WriteRows(pixels, height, 0, Ct)); + Should.Throw(() => session.Commit(Ct)); + } + + [Fact] + public void A_writer_failure_at_the_trailer_fails_commit_instead_of_leaving_a_truncated_file() + { + // One MCU row: the writer sees the headers, the row, then EOI; it throws on the third. + var pixels = Photo(8, 8, 3, 8); + using var cts = new CancellationTokenSource(); + var output = new CancellingWriter(cts) { Armed = true, ThrowAt = 3 }; + using var session = JpegImageEncoder.Create(output, new JpegEncodeOptions { Subsampling = JpegSubsampling.Chroma444 }); + var frame = session.AddFrame(8, 8, PixelFormat.Rgb24); + Should.Throw(() => frame.WriteRows(pixels, 8, 0, Ct)); + Should.Throw(() => session.Commit(Ct)); + } + + private sealed class CancellingWriter(CancellationTokenSource cts) : IBufferWriter + { + private readonly byte[] _buffer = new byte[1 << 16]; + + public bool Armed { get; set; } + + public int Advances { get; private set; } + + /// When set, the advance with this (1-based) number throws instead of cancelling. + public int ThrowAt { get; init; } + + public void Advance(int count) + { + if (!Armed) return; + Advances++; + if (ThrowAt > 0) + { + if (Advances == ThrowAt) throw new IOException("disk full"); + return; + } + cts.Cancel(); + } + + public Memory GetMemory(int sizeHint = 0) => _buffer; + + public Span GetSpan(int sizeHint = 0) => _buffer; + } + + /// An that counts what it is given and keeps none of it. + private sealed class CountingWriter : IBufferWriter + { + private byte[] _buffer = new byte[1 << 16]; + + public long Count { get; private set; } + + public void Advance(int count) => Count += count; + + public Memory GetMemory(int sizeHint = 0) + { + if (sizeHint > _buffer.Length) _buffer = new byte[sizeHint]; + return _buffer; + } + + public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; + } + + [Fact] + public void A_large_frame_streams_in_bounded_memory() + { + // 8192 × 8192 RGB is 192 MiB of pixels; the session holds one 16-row band of it. + const int width = 8192, height = 8192, bandRows = 64; + var band = new byte[width * bandRows * 3]; + FillPhoto(band, width, 0, bandRows, 3, 1); + var writer = new CountingWriter(); + var options = new JpegEncodeOptions { Quality = 75, Subsampling = JpegSubsampling.Chroma420 }; + StreamingAssert.AllocatesLessThan(1 << 20, () => + { + using var session = JpegImageEncoder.Create(writer, options); + var frame = session.AddFrame(width, height, PixelFormat.Rgb24); + for (var y = 0; y < height; y += bandRows) + frame.WriteRows(band, bandRows, 0, Ct); + session.Commit(Ct); + }, "8192x8192 streamed"); + writer.Count.ShouldBeGreaterThan(1 << 20); + } + + /// A writer that hands every advanced span straight to a . + private sealed class FileWriter(FileStream file) : IBufferWriter + { + private byte[] _buffer = new byte[4096]; + + public void Advance(int count) + { + file.Write(_buffer, 0, count); + file.Flush(); + } + + public Memory GetMemory(int sizeHint = 0) + { + if (sizeHint > _buffer.Length) _buffer = new byte[sizeHint]; + return _buffer; + } + + public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; + } + + [Fact] + public void A_photo_streamed_to_a_file_decodes_like_the_buffered_encode() + { + const int width = 3001, height = 2003, bandRows = 37; + var options = new JpegEncodeOptions { Quality = 85, RestartInterval = 64 }; + var pixels = Photo(width, height, 3, 8); + var path = Path.Combine(Path.GetTempPath(), $"jpeg-stream-{Guid.NewGuid():N}.jpg"); + try + { + using (var file = new FileStream(path, FileMode.CreateNew)) + { + using var session = JpegImageEncoder.Create(new FileWriter(file), options); + var frame = session.AddFrame(width, height, PixelFormat.Rgb24); + for (var y = 0; y < height; y += bandRows) + { + var n = Math.Min(bandRows, height - y); + frame.WriteRows(pixels.AsSpan(y * width * 3), n, 0, Ct); + if (y == 0) file.Length.ShouldBeGreaterThan(0, "the first band is on disk before the rest arrives"); + } + session.Commit(Ct); + } + + var streamed = File.ReadAllBytes(path); + var buffered = JpegEncoder.Encode(pixels, width, height, 3, options); + JpegDecoder.Decode(streamed).Pixels.ShouldBe(JpegDecoder.Decode(buffered).Pixels, "our decoder"); + MagickRgb(streamed).ShouldBe(MagickRgb(buffered), "Magick.NET"); + streamed.ShouldBe(buffered); + } + finally + { + File.Delete(path); + } + } + + private static byte[] MagickRgb(byte[] jpeg) + { + using var image = new MagickImage(jpeg, MagickFormat.Jpeg); + using var pixels = image.GetPixels(); + return pixels.ToByteArray(PixelMapping.RGB)!; + } +}