From 7cc6137b5972521300f7061c2f7deefd2e53ab8e Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:52:33 +0800 Subject: [PATCH] PNG: streaming encoder session PngImageEncoder.Create now returns a StreamingEncoderSession for a still image: signature, IHDR and the pre-IDAT chunks at AddFrame, each band of rows filtered and deflated as it arrives and emitted as complete 64 KiB IDAT chunks, the trailing chunks and IEND at Commit. Memory is a band of rows. With ParallelFragments the bands are PngWriter's fragments (capped at 2 MiB of rows) compressed on min(ParallelFragments, ProcessorCount) workers and emitted in order. The zlib stream equals PngWriter's (serial, and parallel up to the cap); only the IDAT packaging differs, +12 bytes per 64 KiB (+0.018%). A file whose zlib stream fits 64 KiB is byte-identical. Band boundaries depend only on the image size and options, never on WriteRows chunking. LosslessReduction, Quantize and the new PngWriteOptions.Animation keep the buffered session (IsStreaming false, bytes unchanged). API break: a session of several frames (APNG) now needs Animation = true; without it a PNG session holds one frame. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- README.zh-CN.md | 2 +- .../Contestants.cs | 46 +- .../Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs | 36 +- .../PngBenchmarks.cs | 8 +- .../Sdcb.SimdCodecs.Png.Benchmarks/README.md | 1 + ...ing-encode-2026-11-23-amd-ryzen-7-5800x.md | 299 ++++++++++++ docs/known-gaps.md | 2 +- src/Sdcb.SimdCodecs.Png/PngImageEncoder.cs | 73 ++- .../PngStreamingSession.cs | 446 ++++++++++++++++++ src/Sdcb.SimdCodecs.Png/PngWriteOptions.cs | 9 + src/Sdcb.SimdCodecs.Png/PngWriter.cs | 6 +- .../PublicAPI.Unshipped.txt | 2 + tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs | 2 +- .../PngApngEncoderTests.cs | 6 +- .../PngStreamingEncodeTests.cs | 437 +++++++++++++++++ 16 files changed, 1338 insertions(+), 39 deletions(-) create mode 100644 benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/results/streaming-encode-2026-11-23-amd-ryzen-7-5800x.md create mode 100644 src/Sdcb.SimdCodecs.Png/PngStreamingSession.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/PngStreamingEncodeTests.cs diff --git a/README.md b/README.md index ae4e09e..109b02d 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ Upgrading from 1.x: [docs/migrating-to-2.0.md](docs/migrating-to-2.0.md). Feature details per package - **Jpeg**: T.81 decoder: baseline, progressive, restart intervals, any subsampling, grey / YCbCr / RGB / CMYK / YCCK, scaled 1/2–1/8 decode, lossless (SOF3, through `LosslessJpeg.FromMemory`). SIMD encoder: baseline, optimised Huffman or progressive; 4:4:4 / 4:2:0 / grey; restart intervals; embeds EXIF (APP1), XMP and an ICC profile (APP2). -- **Png**: every standard bit depth (including 1/2/4-bit grey and indexed), tEXt / zTXt / iTXt text chunks, PNG-3 cICP / mDCV / cLLI HDR signalling. `PngWriteOptions.Quantize` reduces an image to at most 256 colours, translucency included, the way pngquant does: smaller than pngquant's file at equal SSIM on the benchmark corpus (`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`). APNG: `PngAnimationDecoder` composites every dispose / blend operation and seeks; `PngAnimationEncoder` writes changed rectangles, merging unchanged frames. +- **Png**: every standard bit depth (including 1/2/4-bit grey and indexed), tEXt / zTXt / iTXt text chunks, PNG-3 cICP / mDCV / cLLI HDR signalling. `PngWriteOptions.Quantize` reduces an image to at most 256 colours, translucency included, the way pngquant does: smaller than pngquant's file at equal SSIM on the benchmark corpus (`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`). APNG: `PngAnimationDecoder` composites every dispose / blend operation and seeks; `PngAnimationEncoder` writes changed rectangles, merging unchanged frames. The encoder session (`ImageCodecs.CreateEncoder`, `PngImageEncoder.Create`) streams a still image: IDAT chunks reach the writer as row bands are encoded, memory is a band of rows, and pixels and size (+0.02%) match `PngWriter`; `LosslessReduction` and `Quantize` need the whole image and buffer it, and a session of several frames (APNG) needs `PngWriteOptions.Animation`. - **Tiff**: multi-page, classic and BigTIFF; 8/16/32-bit integer and float; Deflate / LZW (+ PackBits and JPEG read, with JPEGTables); strips or tiles; chunky or planar; on-demand single strip or tile reads, and a region decode that reads only the segments it touches; reads 1/2/4-bit pages (expanded to 8-bit), CCITT fax (Group 3 1D/2D, Group 4, Modified Huffman) and the floating-point predictor; the facade presents palette, CMYK and YCbCr pages as RGB and extra samples as alpha. Writes Deflate. - **Webp**: RFC 6386 / RFC 9649: VP8 lossy, VP8L lossless, ALPH, animation with seek, ICC / EXIF / XMP. `WebpAnimationDecoder` adds seeking by timestamp and the frame rectangles. `WebpEncoder.EncodeLossless` writes VP8L stills with alpha, effort 0–9; `WebpEncoder.EncodeLossy` writes VP8 stills, quality 0–100 and effort 0–6, with transparency in an ALPH plane; both can embed ICC / Exif / XMP. `WebpAnimationEncoder` and `WebpEncoder.EncodeAnimation` write animations, lossy, lossless or the smaller per frame, from whole canvases (reduced to the changed rectangle, unchanged frames merged) or from ANMF frames as given. - **Gif**: GIF89a: global / local colour tables, interlacing, transparency, all disposal methods, NETSCAPE2.0 loop count; composited frames with seek. Encoder: stills and animations, exact palettes or perceptual quantization (OKLab box split + k-means) with optional edge-aware Floyd–Steinberg dithering, changed-rectangle frames for opaque animations. The decisions the spec leaves open are listed in the package README. diff --git a/README.zh-CN.md b/README.zh-CN.md index f2a1bd7..035dd46 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -105,7 +105,7 @@ ImageCodecs.Register(HeifImageDecoder.Registration); 各包的详细特性 - **Jpeg**:T.81 解码器,支持 baseline、progressive、restart interval、任意采样方式,灰度 / YCbCr / RGB / CMYK / YCCK,1/2–1/8 缩放解码,无损(SOF3,经由 `LosslessJpeg.FromMemory`)。SIMD 编码器支持 baseline、优化 Huffman 或 progressive;4:4:4 / 4:2:0 / 灰度;restart interval;可写入 EXIF(APP1)、XMP 和 ICC 配置文件(APP2)。 -- **Png**:所有标准位深(包括 1/2/4 位灰度和调色板),tEXt / zTXt / iTXt 文本块,PNG-3 的 cICP / mDCV / cLLI HDR 标记。`PngWriteOptions.Quantize` 像 pngquant 一样把图片降到最多 256 色(含半透明):在基准语料上,同等 SSIM 下文件比 pngquant 的小(`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`)。APNG:`PngAnimationDecoder` 支持所有 dispose / blend 操作并可跳帧;`PngAnimationEncoder` 只写变化矩形,并合并不变的帧。 +- **Png**:所有标准位深(包括 1/2/4 位灰度和调色板),tEXt / zTXt / iTXt 文本块,PNG-3 的 cICP / mDCV / cLLI HDR 标记。`PngWriteOptions.Quantize` 像 pngquant 一样把图片降到最多 256 色(含半透明):在基准语料上,同等 SSIM 下文件比 pngquant 的小(`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`)。APNG:`PngAnimationDecoder` 支持所有 dispose / blend 操作并可跳帧;`PngAnimationEncoder` 只写变化矩形,并合并不变的帧。编码会话(`ImageCodecs.CreateEncoder`、`PngImageEncoder.Create`)流式写静态图:每编码完一批行,IDAT 块就交给写入器,内存只占一批行,像素和大小(+0.02%)与 `PngWriter` 一致;`LosslessReduction` 和 `Quantize` 需要整幅图,会先缓存;多帧会话(APNG)需设置 `PngWriteOptions.Animation`。 - **Tiff**:多页,经典 TIFF 和 BigTIFF;8/16/32 位整数和浮点;Deflate / LZW(另可读 PackBits 和带 JPEGTables 的 JPEG);条带或分块;chunky 或 planar;按需读取单个条带或分块,区域解码只读与区域相交的条带或分块;读取 1/2/4 位页面(扩展为 8 位)、CCITT 传真(Group 3 1D/2D、Group 4、Modified Huffman)和浮点预测器;门面把调色板、CMYK、YCbCr 页面呈现为 RGB,额外采样呈现为 alpha。写入用 Deflate。 - **Webp**:RFC 6386 / RFC 9649:VP8 有损、VP8L 无损、ALPH、带跳转的动画、ICC / EXIF / XMP。`WebpAnimationDecoder` 另外提供按时间戳定位和每帧的矩形。`WebpEncoder.EncodeLossless` 编码 VP8L 静态图(含 alpha),压缩力度 0–9;`WebpEncoder.EncodeLossy` 编码 VP8 静态图,质量 0–100、力度 0–6,透明度写进 ALPH 平面;两者都可写入 ICC / Exif / XMP。`WebpAnimationEncoder` 和 `WebpEncoder.EncodeAnimation` 编码动画:有损、无损,或每帧取两者中较小的;输入可以是整帧画布(只写变化的矩形,合并不变的帧),也可以是调用方给定的 ANMF 帧。 - **Gif**:GIF89a:全局 / 局部调色板、隔行、透明、全部 dispose 方式、NETSCAPE2.0 循环次数;合成好的帧,可跳转。编码器:静态图和动画,精确调色板或感知量化(OKLab 盒切分 + k-means,可选边缘自适应的 Floyd–Steinberg 抖动),不透明动画只写变化的矩形。规范没有定死的行为列在包的 README 里。 diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs index 98792e9..8bac9e5 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs @@ -1,6 +1,8 @@ +using System.Buffers; using System.Buffers.Binary; using System.IO.Compression; using System.Runtime.InteropServices; +using Sdcb.SimdCodecs.Abstractions; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Png; @@ -17,6 +19,8 @@ internal static class Names public const string CurrentNative = "CurrentNative"; public const string CurrentParallel = "CurrentParallel"; public const string CurrentReduced = "CurrentReduced"; + public const string Streaming = "Streaming"; + public const string StreamingParallel = "StreamingParallel"; public const string Baseline = "Baseline"; public const string ImageSharp = "ImageSharp"; public const string LibPng = "LibPng"; @@ -258,7 +262,7 @@ void Add(string name, Func encode, Action? timed = null) byte[] output = encode(); if ((lossless ? VerifyLossless(output, c, samples) : Verify(output, c, samples)) is { } problem) { - if (name is Names.Current or Names.CurrentParallel or Names.CurrentReduced) + if (name is Names.Current or Names.CurrentParallel or Names.CurrentReduced or Names.Streaming or Names.StreamingParallel) { throw new InvalidOperationException($"{c.Name}: {name} output is wrong ({problem}); refusing to benchmark."); } @@ -277,6 +281,12 @@ void Add(string name, Func encode, Action? timed = null) Add(Names.CurrentParallel, () => EncodeCurrent(c.Format, samples, width, height, parallel)); var reduced = options with { LosslessReduction = true }; Add(Names.CurrentReduced, () => EncodeCurrent(c.Format, samples, width, height, reduced)); + // The PngImageEncoder session, rows pushed in bands of 16 as a row producer would: streaming, IDATs leaving per band. + var streamOutput = new ArrayBufferWriter(); + Add(Names.Streaming, () => EncodeSession(c.Format, samples, width, height, options, streamOutput).ToArray(), + () => Sink = EncodeSession(c.Format, samples, width, height, options, streamOutput).Length); + Add(Names.StreamingParallel, () => EncodeSession(c.Format, samples, width, height, parallel, streamOutput).ToArray(), + () => Sink = EncodeSession(c.Format, samples, width, height, parallel, streamOutput).Length); if (only is null) { var header = PngReader.Decode(EncodeCurrent(c.Format, samples, width, height, reduced)); @@ -323,6 +333,40 @@ void Add(string name, Func encode, Action? timed = null) return setup; } + /// Rows per WriteRows call of the session contestants. + public const int SessionBand = 16; + + private static ReadOnlyMemory EncodeSession(EncodeFormat format, byte[] samples, int width, int height, PngWriteOptions options, + ArrayBufferWriter output) + { + var pixelFormat = format switch + { + EncodeFormat.Gray8 => PixelFormat.Gray8, + EncodeFormat.Rgb8 => PixelFormat.Rgb24, + EncodeFormat.Rgba8 => PixelFormat.Rgba32, + EncodeFormat.Gray16 => PixelFormat.Gray16, + EncodeFormat.Rgb16 => PixelFormat.Rgb48, + _ => PixelFormat.Rgba64, + }; + output.ResetWrittenCount(); + using var session = PngImageEncoder.Create(output, options); + if (!session.IsStreaming) + { + throw new InvalidOperationException("The PNG session does not stream these options."); + } + + var frame = session.AddFrame(width, height, pixelFormat); + var rowBytes = width * pixelFormat.BytesPerPixel; + for (var y = 0; y < height; y += SessionBand) + { + var n = Math.Min(SessionBand, height - y); + frame.WriteRows(samples.AsSpan(y * rowBytes, n * rowBytes), n); + } + + session.Commit(); + return output.WrittenMemory; + } + private static byte[] EncodeCurrent(EncodeFormat format, byte[] samples, int width, int height, PngWriteOptions options) => format switch { EncodeFormat.Gray8 => PngWriter.EncodeGray8(samples, width, height, options), diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs index 181cbbd..8a3b829 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs @@ -214,6 +214,32 @@ public static string RenderEncode(IReadOnlyList<(EncodeSetup Setup, Dictionary r.Ms.ContainsKey(Names.Streaming))) + { + sb.AppendLine(); + sb.AppendLine($"Streaming session (`PngImageEncoder.Create`, rows pushed {EncodeSetup.SessionBand} at a time, IDATs leaving per band) " + + "against the buffered `PngWriter` call with the same options: one thread, then `ParallelFragments = " + + $"{EncodeSetup.ParallelFragments}`:"); + sb.AppendLine(); + sb.AppendLine("| Case | current | streaming | time ÷ current | size ÷ current | parallel | streaming parallel | time ÷ parallel | size ÷ parallel |"); + sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|---:|"); + foreach ((EncodeSetup s, Dictionary ms) in rows) + { + sb.AppendLine($"| `{s.Case.Name}` | {Ms(ms, Names.Current)} | {Ms(ms, Names.Streaming)} | {Ratio(ms, Names.Streaming, Names.Current)} | " + + $"{SizeOf(s, Names.Streaming, Names.Current)} | {Ms(ms, Names.CurrentParallel)} | {Ms(ms, Names.StreamingParallel)} | " + + $"{Ratio(ms, Names.StreamingParallel, Names.CurrentParallel)} | {SizeOf(s, Names.StreamingParallel, Names.CurrentParallel)} |"); + } + + if (GeoMean(rows.Select(r => r.Ms).ToList(), Names.Streaming, Names.Current) is { } g1) + { + sb.AppendLine(); + sb.AppendLine($"Geometric mean streaming ÷ current: {g1.ToString("F3", CultureInfo.InvariantCulture)}×"); + } + + if (GeoMean(rows.Select(r => r.Ms).ToList(), Names.StreamingParallel, Names.CurrentParallel) is { } g2) + sb.AppendLine($"Geometric mean streaming parallel ÷ parallel: {g2.ToString("F3", CultureInfo.InvariantCulture)}×"); + } + if (rows.Any(r => r.Ms.ContainsKey(Names.CurrentReduced))) { sb.AppendLine(); @@ -234,7 +260,7 @@ public static string RenderEncode(IReadOnlyList<(EncodeSetup Setup, Dictionary (r.Setup.Case.Name, r.Setup.Allocated)).ToList(), - [Names.Current, Names.CurrentParallel, Names.CurrentReduced, Names.Baseline, Names.ImageSharp, Names.LibPng]); + [Names.Current, Names.CurrentParallel, Names.CurrentReduced, Names.Streaming, Names.StreamingParallel, Names.Baseline, Names.ImageSharp, Names.LibPng]); AppendNotes(sb, notes); return sb.ToString(); } @@ -284,6 +310,8 @@ private static void AppendNotes(StringBuilder sb, List notes) Names.CurrentNative => "native", Names.CurrentParallel => "parallel", Names.CurrentReduced => "reduced", + Names.Streaming => "streaming", + Names.StreamingParallel => "streaming parallel", _ => name, }; @@ -310,6 +338,12 @@ private static string SizeRatio(EncodeSetup s, string competitor) => ? ((double)a / b).ToString("F3", CultureInfo.InvariantCulture) : "—"; + /// Size of over to five places: streaming moves sizes by hundredths of a percent. + private static string SizeOf(EncodeSetup s, string a, string b) => + s.Sizes.TryGetValue(a, out int x) && s.Sizes.TryGetValue(b, out int y) + ? ((double)x / y).ToString("F5", CultureInfo.InvariantCulture) + : "—"; + private static double Median(List values) { values.Sort(); diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs index 0efb3cc..256fc15 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs @@ -73,6 +73,12 @@ public class PngEncodeBenchmarks [Benchmark] public void CurrentParallel() => _run[Names.CurrentParallel](); + [Benchmark] + public void Streaming() => _run[Names.Streaming](); + + [Benchmark] + public void StreamingParallel() => _run[Names.StreamingParallel](); + [Benchmark] public void Baseline() => _run[Names.Baseline](); @@ -82,7 +88,7 @@ public class PngEncodeBenchmarks [Benchmark] public void LibPng() => _run[Names.LibPng](); - public static readonly string[] Methods = [Names.Current, Names.CurrentParallel, Names.Baseline, Names.ImageSharp, Names.LibPng]; + public static readonly string[] Methods = [Names.Current, Names.CurrentParallel, Names.Streaming, Names.StreamingParallel, Names.Baseline, Names.ImageSharp, Names.LibPng]; } /// Runs every contestant on one case before moving to the next. diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md index 644dbe7..9b2b51b 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md @@ -27,6 +27,7 @@ Decode inputs are encoded by ImageSharp (adaptive filters, zlib level 6) — a f | `current` | `PngImageDecoder.TryDecodeIntoRgba8` into a reused buffer | `PngWriter.Encode*` with `PngWriteOptions.CompressionLevel` | | `native` (decode) | `PngReader.Decode`: samples as stored, no RGBA expansion | — | | `parallel` (encode) | — | the same with `ParallelFragments = Environment.ProcessorCount`; reported in its own table, never in the single-thread ratios | +| `streaming` / `streaming parallel` (encode) | — | the `PngImageEncoder` session (streaming: `IDAT` chunks leave per band), rows pushed 16 at a time, without and with `ParallelFragments`; its own table against `current` and `parallel` | | `reduced` (encode) | — | the same with `LosslessReduction = true` (the smallest exact layout: indexed, sub-byte grey, tRNS, ...); its own table, with the layout chosen | | `baseline` | the previous commit's decoder, same process (see below) | the previous commit's encoder | | ImageSharp 3.1.12 | `Image.Load` + `CopyPixelDataTo`, `MaxDegreeOfParallelism = 1` | `PngEncoder` with the same colour type, depth and zlib level (0 / 1 / 6 / 9), adaptive filters | diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/results/streaming-encode-2026-11-23-amd-ryzen-7-5800x.md b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/results/streaming-encode-2026-11-23-amd-ryzen-7-5800x.md new file mode 100644 index 0000000..b80d8a8 --- /dev/null +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/results/streaming-encode-2026-11-23-amd-ryzen-7-5800x.md @@ -0,0 +1,299 @@ +# Streaming PNG encode, 2026-11-23 + +The `PngImageEncoder` streaming session (`streaming`, `streaming parallel`) against the buffered `PngWriter` call with the same options, and the encoder against the `baseline` build of main (533b03e), whose `PngWriter` code this change does not alter (geometric mean current ÷ baseline over the 48 cases: 1.005×; the scatter of single cases, 0.85–1.20×, is this machine's noise: other builds were running). `matrix encode --rounds 7`, synthetic sources. + +- CPU: AMD Ryzen 7 5800X 8-Core Processor +- OS: Microsoft Windows 10.0.26200 (X64) +- .NET: .NET 10.0.15 (win-x64), process X64 +- Logical processors: 16 +- Vector128.IsHardwareAccelerated: True, Vector256.IsHardwareAccelerated: True, Vector512.IsHardwareAccelerated: False +- AVX2: True, AVX-512F: False +- Image size: 1920×1080 +- `photo` source: synthetic (no JPEG corpus master found; run the JPEG benchmark's scripts/fetch-corpus.sh for a real photo) +- `screen` source: synthetic +- ImageSharp: 3.1.12 +- libpng: not found (tried libpng16.dll, libpng.dll; set LIBPNG_PATH) +- Baseline: 533b03e2f35a Merge feature/streaming-foundation: streaming plumbing in Abstractions + +### Encode (in-process medians of 7 interleaved rounds, ms; sizes in KB) + +`current` = `PngWriter.Encode*` with `PngWriteOptions.CompressionLevel`, one thread; ImageSharp = `PngEncoder` at the same zlib level (store 0, fastest 1, optimal 6, smallest 9), adaptive filters, one thread; libpng = simplified API `png_image_write_to_memory`, which has no level setting, so it appears on the optimal rows (its default). Every output is decoded and must reproduce the samples exactly. + +| Case | current | KB | baseline | ImageSharp | KB | libpng | KB | time ÷ ImageSharp | size ÷ ImageSharp | time ÷ libpng | size ÷ libpng | time ÷ baseline | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| `photo-gray8-store` | 1.795 | 2026 | 1.850 | 3.417 | 2027 | — | — | 0.53× | 1.000 | — | — | 0.97× | +| `photo-gray8-fastest` | 38.2 | 1737 | 37.7 | 30.4 | 1174 | — | — | 1.26× | 1.479 | — | — | 1.01× | +| `photo-gray8-optimal` | 51.7 | 1095 | 52.4 | 85.3 | 1129 | — | — | 0.61× | 0.970 | — | — | 0.99× | +| `photo-gray8-smallest` | 101.4 | 1136 | 100.4 | 85.4 | 1129 | — | — | 1.19× | 1.007 | — | — | 1.01× | +| `photo-gray16-store` | 3.721 | 4052 | 4.041 | 7.991 | 4052 | — | — | 0.47× | 1.000 | — | — | 0.92× | +| `photo-gray16-fastest` | 85.5 | 4270 | 85.4 | 112.8 | 3524 | — | — | 0.76× | 1.212 | — | — | 1.00× | +| `photo-gray16-optimal` | 140.0 | 3492 | 145.4 | 126.6 | 3501 | — | — | 1.11× | 0.997 | — | — | 0.96× | +| `photo-gray16-smallest` | 144.2 | 3521 | 145.7 | 125.3 | 3501 | — | — | 1.15× | 1.006 | — | — | 0.99× | +| `photo-rgb8-store` | 7.257 | 6077 | 6.800 | 12.5 | 6078 | — | — | 0.58× | 1.000 | — | — | 1.07× | +| `photo-rgb8-fastest` | 87.2 | 4360 | 88.2 | 94.7 | 2984 | — | — | 0.92× | 1.461 | — | — | 0.99× | +| `photo-rgb8-optimal` | 129.2 | 2727 | 126.6 | 429.2 | 2703 | — | — | 0.30× | 1.009 | — | — | 1.02× | +| `photo-rgb8-smallest` | 386.6 | 2693 | 421.8 | 500.9 | 2695 | — | — | 0.77× | 0.999 | — | — | 0.92× | +| `photo-rgb16-store` | 12.1 | 12153 | 12.4 | 26.1 | 12155 | — | — | 0.47× | 1.000 | — | — | 0.98× | +| `photo-rgb16-fastest` | 276.8 | 12801 | 292.7 | 370.0 | 10602 | — | — | 0.75× | 1.207 | — | — | 0.95× | +| `photo-rgb16-optimal` | 445.7 | 10571 | 438.7 | 397.4 | 10578 | — | — | 1.12× | 0.999 | — | — | 1.02× | +| `photo-rgb16-smallest` | 513.5 | 10593 | 570.1 | 438.7 | 10578 | — | — | 1.17× | 1.001 | — | — | 0.90× | +| `photo-rgba8-store` | 8.451 | 8102 | 8.714 | 14.4 | 8104 | — | — | 0.59× | 1.000 | — | — | 0.97× | +| `photo-rgba8-fastest` | 114.2 | 5019 | 109.0 | 121.4 | 3424 | — | — | 0.94× | 1.466 | — | — | 1.05× | +| `photo-rgba8-optimal` | 298.4 | 3146 | 274.5 | 1021.5 | 3142 | — | — | 0.29× | 1.001 | — | — | 1.09× | +| `photo-rgba8-smallest` | 635.1 | 3120 | 629.3 | 1095.1 | 3117 | — | — | 0.58× | 1.001 | — | — | 1.01× | +| `photo-rgba16-store` | 15.6 | 16204 | 17.6 | 32.1 | 16206 | — | — | 0.49× | 1.000 | — | — | 0.89× | +| `photo-rgba16-fastest` | 347.9 | 16779 | 338.4 | 444.9 | 13529 | — | — | 0.78× | 1.240 | — | — | 1.03× | +| `photo-rgba16-optimal` | 576.9 | 13500 | 549.5 | 667.4 | 13508 | — | — | 0.86× | 0.999 | — | — | 1.05× | +| `photo-rgba16-smallest` | 679.6 | 13508 | 660.4 | 652.3 | 13508 | — | — | 1.04× | 1.000 | — | — | 1.03× | +| `screen-gray8-store` | 1.840 | 2026 | 1.819 | 3.180 | 2027 | — | — | 0.58× | 1.000 | — | — | 1.01× | +| `screen-gray8-fastest` | 15.9 | 115 | 18.6 | 7.077 | 83 | — | — | 2.24× | 1.388 | — | — | 0.85× | +| `screen-gray8-optimal` | 16.8 | 60 | 16.2 | 22.1 | 59 | — | — | 0.76× | 1.019 | — | — | 1.03× | +| `screen-gray8-smallest` | 47.0 | 57 | 46.5 | 129.5 | 57 | — | — | 0.36× | 0.999 | — | — | 1.01× | +| `screen-gray16-store` | 3.715 | 4052 | 3.628 | 7.774 | 4052 | — | — | 0.48× | 1.000 | — | — | 1.02× | +| `screen-gray16-fastest` | 24.4 | 195 | 24.1 | 11.1 | 130 | — | — | 2.20× | 1.493 | — | — | 1.01× | +| `screen-gray16-optimal` | 30.4 | 83 | 30.1 | 32.8 | 83 | — | — | 0.93× | 0.998 | — | — | 1.01× | +| `screen-gray16-smallest` | 77.1 | 82 | 76.0 | 153.6 | 81 | — | — | 0.50× | 1.005 | — | — | 1.01× | +| `screen-rgb8-store` | 5.496 | 6077 | 5.515 | — | — | — | — | — | — | — | — | 1.00× | +| `screen-rgb8-fastest` | 35.7 | 186 | 36.2 | — | — | — | — | — | — | — | — | 0.99× | +| `screen-rgb8-optimal` | 41.6 | 78 | 41.1 | — | — | — | — | — | — | — | — | 1.01× | +| `screen-rgb8-smallest` | 86.7 | 76 | 84.4 | 199.8 | 77 | — | — | 0.43× | 0.982 | — | — | 1.03× | +| `screen-rgb16-store` | 13.3 | 12153 | 14.0 | 29.3 | 12155 | — | — | 0.45× | 1.000 | — | — | 0.95× | +| `screen-rgb16-fastest` | 88.3 | 298 | 85.3 | 32.5 | 176 | — | — | 2.72× | 1.696 | — | — | 1.04× | +| `screen-rgb16-optimal` | 87.3 | 96 | 82.0 | 71.0 | 97 | — | — | 1.23× | 0.984 | — | — | 1.06× | +| `screen-rgb16-smallest` | 138.1 | 90 | 135.2 | 284.0 | 91 | — | — | 0.49× | 0.988 | — | — | 1.02× | +| `screen-rgba8-store` | 7.844 | 8102 | 7.147 | 13.6 | 8104 | — | — | 0.58× | 1.000 | — | — | 1.10× | +| `screen-rgba8-fastest` | 56.6 | 250 | 47.2 | 18.3 | 151 | — | — | 3.09× | 1.657 | — | — | 1.20× | +| `screen-rgba8-optimal` | 57.3 | 85 | 56.9 | 51.1 | 85 | — | — | 1.12× | 0.998 | — | — | 1.01× | +| `screen-rgba8-smallest` | 100.2 | 82 | 96.7 | 240.2 | 83 | — | — | 0.42× | 0.989 | — | — | 1.04× | +| `screen-rgba16-store` | 17.5 | 16204 | 17.1 | 36.0 | 16206 | — | — | 0.48× | 1.000 | — | — | 1.02× | +| `screen-rgba16-fastest` | 93.8 | 341 | 88.4 | 32.9 | 214 | — | — | 2.85× | 1.596 | — | — | 1.06× | +| `screen-rgba16-optimal` | 104.5 | 103 | 99.8 | 78.0 | 106 | — | — | 1.34× | 0.980 | — | — | 1.05× | +| `screen-rgba16-smallest` | 247.7 | 99 | 260.5 | 473.3 | 99 | — | — | 0.52× | 0.996 | — | — | 0.95× | + +Geometric means of current ÷ ImageSharp per compression level (time / size): + +- store: time 0.51×, size 1.000× +- fastest: time 1.44×, size 1.436× +- optimal: time 0.79×, size 0.996× +- smallest: time 0.66×, size 0.998× + +Opt-in parallel deflate (`ParallelFragments = 16`), not part of the single-thread comparison above: + +| Case | current (1 thread) | parallel | speed-up | KB | size ÷ 1 thread | +|---|---:|---:|---:|---:|---:| +| `photo-gray8-store` | 1.795 | 2.756 | 0.65× | 2026 | 1.000 | +| `photo-gray8-fastest` | 38.2 | 8.401 | 4.55× | 1743 | 1.004 | +| `photo-gray8-optimal` | 51.7 | 11.7 | 4.42× | 1095 | 1.000 | +| `photo-gray8-smallest` | 101.4 | 20.7 | 4.89× | 1142 | 1.005 | +| `photo-gray16-store` | 3.721 | 5.340 | 0.70× | 4052 | 1.000 | +| `photo-gray16-fastest` | 85.5 | 18.7 | 4.59× | 4271 | 1.000 | +| `photo-gray16-optimal` | 140.0 | 24.5 | 5.72× | 3492 | 1.000 | +| `photo-gray16-smallest` | 144.2 | 25.6 | 5.63× | 3522 | 1.000 | +| `photo-rgb8-store` | 7.257 | 9.039 | 0.80× | 6077 | 1.000 | +| `photo-rgb8-fastest` | 87.2 | 19.6 | 4.45× | 4372 | 1.003 | +| `photo-rgb8-optimal` | 129.2 | 23.5 | 5.50× | 2748 | 1.008 | +| `photo-rgb8-smallest` | 386.6 | 73.7 | 5.25× | 2714 | 1.008 | +| `photo-rgb16-store` | 12.1 | 15.7 | 0.77× | 12153 | 1.000 | +| `photo-rgb16-fastest` | 276.8 | 55.7 | 4.97× | 12801 | 1.000 | +| `photo-rgb16-optimal` | 445.7 | 73.1 | 6.10× | 10571 | 1.000 | +| `photo-rgb16-smallest` | 513.5 | 90.5 | 5.67× | 10595 | 1.000 | +| `photo-rgba8-store` | 8.451 | 10.4 | 0.81× | 8102 | 1.000 | +| `photo-rgba8-fastest` | 114.2 | 25.5 | 4.48× | 5025 | 1.001 | +| `photo-rgba8-optimal` | 298.4 | 46.4 | 6.43× | 3164 | 1.006 | +| `photo-rgba8-smallest` | 635.1 | 75.2 | 8.45× | 3137 | 1.006 | +| `photo-rgba16-store` | 15.6 | 21.5 | 0.73× | 16204 | 1.000 | +| `photo-rgba16-fastest` | 347.9 | 71.3 | 4.88× | 16782 | 1.000 | +| `photo-rgba16-optimal` | 576.9 | 87.0 | 6.63× | 13500 | 1.000 | +| `photo-rgba16-smallest` | 679.6 | 98.9 | 6.87× | 13511 | 1.000 | +| `screen-gray8-store` | 1.840 | 2.491 | 0.74× | 2026 | 1.000 | +| `screen-gray8-fastest` | 15.9 | 3.841 | 4.14× | 115 | 1.001 | +| `screen-gray8-optimal` | 16.8 | 4.017 | 4.18× | 60 | 0.995 | +| `screen-gray8-smallest` | 47.0 | 10.9 | 4.33× | 57 | 1.002 | +| `screen-gray16-store` | 3.715 | 4.730 | 0.79× | 4052 | 1.000 | +| `screen-gray16-fastest` | 24.4 | 3.670 | 6.66× | 195 | 1.002 | +| `screen-gray16-optimal` | 30.4 | 4.556 | 6.68× | 83 | 0.998 | +| `screen-gray16-smallest` | 77.1 | 10.7 | 7.17× | 82 | 1.001 | +| `screen-rgb8-store` | 5.496 | 6.918 | 0.79× | 6077 | 1.000 | +| `screen-rgb8-fastest` | 35.7 | 7.608 | 4.70× | 186 | 1.001 | +| `screen-rgb8-optimal` | 41.6 | 7.314 | 5.69× | 78 | 1.002 | +| `screen-rgb8-smallest` | 86.7 | 11.6 | 7.46× | 76 | 1.003 | +| `screen-rgb16-store` | 13.3 | 18.4 | 0.73× | 12153 | 1.000 | +| `screen-rgb16-fastest` | 88.3 | 19.7 | 4.48× | 298 | 1.000 | +| `screen-rgb16-optimal` | 87.3 | 18.7 | 4.67× | 96 | 1.004 | +| `screen-rgb16-smallest` | 138.1 | 24.0 | 5.75× | 90 | 1.005 | +| `screen-rgba8-store` | 7.844 | 10.5 | 0.75× | 8102 | 1.000 | +| `screen-rgba8-fastest` | 56.6 | 12.0 | 4.71× | 250 | 0.999 | +| `screen-rgba8-optimal` | 57.3 | 12.5 | 4.59× | 86 | 1.004 | +| `screen-rgba8-smallest` | 100.2 | 14.0 | 7.18× | 83 | 1.007 | +| `screen-rgba16-store` | 17.5 | 23.2 | 0.75× | 16204 | 1.000 | +| `screen-rgba16-fastest` | 93.8 | 18.4 | 5.10× | 341 | 1.000 | +| `screen-rgba16-optimal` | 104.5 | 19.2 | 5.43× | 104 | 1.003 | +| `screen-rgba16-smallest` | 247.7 | 41.7 | 5.94× | 99 | 1.005 | + +Streaming session (`PngImageEncoder.Create`, rows pushed 16 at a time, IDATs leaving per band) against the buffered `PngWriter` call with the same options: one thread, then `ParallelFragments = 16`: + +| Case | current | streaming | time ÷ current | size ÷ current | parallel | streaming parallel | time ÷ parallel | size ÷ parallel | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| `photo-gray8-store` | 1.795 | 1.426 | 0.79× | 1.00018 | 2.756 | 2.165 | 0.79× | 1.00018 | +| `photo-gray8-fastest` | 38.2 | 37.8 | 0.99× | 1.00018 | 8.401 | 7.255 | 0.86× | 1.00018 | +| `photo-gray8-optimal` | 51.7 | 51.3 | 0.99× | 1.00018 | 11.7 | 11.6 | 0.99× | 1.00018 | +| `photo-gray8-smallest` | 101.4 | 100.7 | 0.99× | 1.00018 | 20.7 | 20.2 | 0.97× | 1.00017 | +| `photo-gray16-store` | 3.721 | 2.787 | 0.75× | 1.00018 | 5.340 | 3.940 | 0.74× | 1.00018 | +| `photo-gray16-fastest` | 85.5 | 84.3 | 0.99× | 1.00018 | 18.7 | 15.0 | 0.80× | 1.00018 | +| `photo-gray16-optimal` | 140.0 | 138.4 | 0.99× | 1.00018 | 24.5 | 23.4 | 0.95× | 1.00018 | +| `photo-gray16-smallest` | 144.2 | 147.7 | 1.02× | 1.00018 | 25.6 | 22.7 | 0.89× | 1.00018 | +| `photo-rgb8-store` | 7.257 | 5.169 | 0.71× | 1.00018 | 9.039 | 5.558 | 0.61× | 1.00018 | +| `photo-rgb8-fastest` | 87.2 | 91.8 | 1.05× | 1.00018 | 19.6 | 15.4 | 0.78× | 1.00018 | +| `photo-rgb8-optimal` | 129.2 | 127.1 | 0.98× | 1.00018 | 23.5 | 20.2 | 0.86× | 1.00018 | +| `photo-rgb8-smallest` | 386.6 | 400.6 | 1.04× | 1.00018 | 73.7 | 55.6 | 0.75× | 1.00018 | +| `photo-rgb16-store` | 12.1 | 9.102 | 0.75× | 1.00018 | 15.7 | 11.1 | 0.71× | 1.00018 | +| `photo-rgb16-fastest` | 276.8 | 310.4 | 1.12× | 1.00018 | 55.7 | 47.0 | 0.84× | 1.00018 | +| `photo-rgb16-optimal` | 445.7 | 457.1 | 1.03× | 1.00018 | 73.1 | 65.2 | 0.89× | 1.00018 | +| `photo-rgb16-smallest` | 513.5 | 567.8 | 1.11× | 1.00018 | 90.5 | 75.6 | 0.83× | 1.00018 | +| `photo-rgba8-store` | 8.451 | 5.623 | 0.67× | 1.00018 | 10.4 | 6.804 | 0.66× | 1.00018 | +| `photo-rgba8-fastest` | 114.2 | 106.3 | 0.93× | 1.00018 | 25.5 | 21.7 | 0.85× | 1.00018 | +| `photo-rgba8-optimal` | 298.4 | 313.4 | 1.05× | 1.00018 | 46.4 | 41.5 | 0.90× | 1.00018 | +| `photo-rgba8-smallest` | 635.1 | 626.6 | 0.99× | 1.00018 | 75.2 | 72.2 | 0.96× | 1.00018 | +| `photo-rgba16-store` | 15.6 | 12.1 | 0.77× | 1.00018 | 21.5 | 15.4 | 0.71× | 1.00018 | +| `photo-rgba16-fastest` | 347.9 | 342.4 | 0.98× | 1.00018 | 71.3 | 58.4 | 0.82× | 1.00018 | +| `photo-rgba16-optimal` | 576.9 | 555.4 | 0.96× | 1.00018 | 87.0 | 77.8 | 0.89× | 1.00018 | +| `photo-rgba16-smallest` | 679.6 | 673.4 | 0.99× | 1.00018 | 98.9 | 90.4 | 0.91× | 1.00018 | +| `screen-gray8-store` | 1.840 | 1.528 | 0.83× | 1.00018 | 2.491 | 2.140 | 0.86× | 1.00018 | +| `screen-gray8-fastest` | 15.9 | 17.1 | 1.07× | 1.00010 | 3.841 | 4.675 | 1.22× | 1.00010 | +| `screen-gray8-optimal` | 16.8 | 17.3 | 1.03× | 1.00000 | 4.017 | 4.494 | 1.12× | 1.00000 | +| `screen-gray8-smallest` | 47.0 | 47.0 | 1.00× | 1.00000 | 10.9 | 10.9 | 1.01× | 1.00000 | +| `screen-gray16-store` | 3.715 | 2.784 | 0.75× | 1.00018 | 4.730 | 3.815 | 0.81× | 1.00018 | +| `screen-gray16-fastest` | 24.4 | 24.4 | 1.00× | 1.00018 | 3.670 | 3.713 | 1.01× | 1.00018 | +| `screen-gray16-optimal` | 30.4 | 30.6 | 1.01× | 1.00014 | 4.556 | 4.604 | 1.01× | 1.00014 | +| `screen-gray16-smallest` | 77.1 | 77.5 | 1.01× | 1.00014 | 10.7 | 10.6 | 0.99× | 1.00014 | +| `screen-rgb8-store` | 5.496 | 4.149 | 0.75× | 1.00018 | 6.918 | 5.260 | 0.76× | 1.00018 | +| `screen-rgb8-fastest` | 35.7 | 35.8 | 1.00× | 1.00013 | 7.608 | 7.000 | 0.92× | 1.00013 | +| `screen-rgb8-optimal` | 41.6 | 41.3 | 0.99× | 1.00015 | 7.314 | 7.164 | 0.98× | 1.00015 | +| `screen-rgb8-smallest` | 86.7 | 86.7 | 1.00× | 1.00015 | 11.6 | 11.8 | 1.01× | 1.00015 | +| `screen-rgb16-store` | 13.3 | 9.399 | 0.71× | 1.00018 | 18.4 | 13.4 | 0.73× | 1.00018 | +| `screen-rgb16-fastest` | 88.3 | 93.0 | 1.05× | 1.00016 | 19.7 | 18.8 | 0.96× | 1.00016 | +| `screen-rgb16-optimal` | 87.3 | 87.5 | 1.00× | 1.00012 | 18.7 | 18.8 | 1.01× | 1.00012 | +| `screen-rgb16-smallest` | 138.1 | 139.6 | 1.01× | 1.00013 | 24.0 | 21.7 | 0.90× | 1.00013 | +| `screen-rgba8-store` | 7.844 | 5.741 | 0.73× | 1.00018 | 10.5 | 6.981 | 0.67× | 1.00018 | +| `screen-rgba8-fastest` | 56.6 | 53.8 | 0.95× | 1.00014 | 12.0 | 11.7 | 0.98× | 1.00014 | +| `screen-rgba8-optimal` | 57.3 | 58.4 | 1.02× | 1.00014 | 12.5 | 13.0 | 1.05× | 1.00014 | +| `screen-rgba8-smallest` | 100.2 | 98.9 | 0.99× | 1.00014 | 14.0 | 12.9 | 0.92× | 1.00014 | +| `screen-rgba16-store` | 17.5 | 11.9 | 0.68× | 1.00018 | 23.2 | 14.9 | 0.64× | 1.00018 | +| `screen-rgba16-fastest` | 93.8 | 95.2 | 1.01× | 1.00017 | 18.4 | 18.1 | 0.98× | 1.00017 | +| `screen-rgba16-optimal` | 104.5 | 105.6 | 1.01× | 1.00011 | 19.2 | 18.6 | 0.97× | 1.00011 | +| `screen-rgba16-smallest` | 247.7 | 302.6 | 1.22× | 1.00012 | 41.7 | 43.8 | 1.05× | 1.00012 | + +Geometric mean streaming ÷ current: 0.938× +Geometric mean streaming parallel ÷ parallel: 0.876× + +Opt-in lossless reduction (`LosslessReduction = true`: the smallest exact layout, found by one scan of the image), not part of the comparison above: + +| Case | current | reduced | time ÷ current | layout | KB | size ÷ current | +|---|---:|---:|---:|---|---:|---:| +| `photo-gray8-store` | 1.795 | 1.923 | 1.07× | grey 8-bit | 2026 | 1.000 | +| `photo-gray8-fastest` | 38.2 | 38.3 | 1.00× | grey 8-bit | 1737 | 1.000 | +| `photo-gray8-optimal` | 51.7 | 52.4 | 1.01× | grey 8-bit | 1095 | 1.000 | +| `photo-gray8-smallest` | 101.4 | 101.4 | 1.00× | grey 8-bit | 1136 | 1.000 | +| `photo-gray16-store` | 3.721 | 4.146 | 1.11× | grey 16-bit | 4052 | 1.000 | +| `photo-gray16-fastest` | 85.5 | 86.0 | 1.01× | grey 16-bit | 4270 | 1.000 | +| `photo-gray16-optimal` | 140.0 | 146.3 | 1.04× | grey 16-bit | 3492 | 1.000 | +| `photo-gray16-smallest` | 144.2 | 147.4 | 1.02× | grey 16-bit | 3521 | 1.000 | +| `photo-rgb8-store` | 7.257 | 6.856 | 0.94× | RGB 8-bit | 6077 | 1.000 | +| `photo-rgb8-fastest` | 87.2 | 95.1 | 1.09× | RGB 8-bit | 4360 | 1.000 | +| `photo-rgb8-optimal` | 129.2 | 128.7 | 1.00× | RGB 8-bit | 2727 | 1.000 | +| `photo-rgb8-smallest` | 386.6 | 420.0 | 1.09× | RGB 8-bit | 2693 | 1.000 | +| `photo-rgb16-store` | 12.1 | 11.9 | 0.98× | RGB 16-bit | 12153 | 1.000 | +| `photo-rgb16-fastest` | 276.8 | 313.6 | 1.13× | RGB 16-bit | 12801 | 1.000 | +| `photo-rgb16-optimal` | 445.7 | 454.0 | 1.02× | RGB 16-bit | 10571 | 1.000 | +| `photo-rgb16-smallest` | 513.5 | 541.1 | 1.05× | RGB 16-bit | 10593 | 1.000 | +| `photo-rgba8-store` | 8.451 | 7.887 | 0.93× | RGBA 8-bit | 8102 | 1.000 | +| `photo-rgba8-fastest` | 114.2 | 114.6 | 1.00× | RGBA 8-bit | 5019 | 1.000 | +| `photo-rgba8-optimal` | 298.4 | 280.3 | 0.94× | RGBA 8-bit | 3146 | 1.000 | +| `photo-rgba8-smallest` | 635.1 | 627.8 | 0.99× | RGBA 8-bit | 3120 | 1.000 | +| `photo-rgba16-store` | 15.6 | 16.3 | 1.04× | RGBA 16-bit | 16204 | 1.000 | +| `photo-rgba16-fastest` | 347.9 | 340.3 | 0.98× | RGBA 16-bit | 16779 | 1.000 | +| `photo-rgba16-optimal` | 576.9 | 558.5 | 0.97× | RGBA 16-bit | 13500 | 1.000 | +| `photo-rgba16-smallest` | 679.6 | 669.4 | 0.99× | RGBA 16-bit | 13508 | 1.000 | +| `screen-gray8-store` | 1.840 | 1.968 | 1.07× | grey 8-bit | 2026 | 1.000 | +| `screen-gray8-fastest` | 15.9 | 18.7 | 1.18× | grey 8-bit | 115 | 1.000 | +| `screen-gray8-optimal` | 16.8 | 16.7 | 0.99× | grey 8-bit | 60 | 1.000 | +| `screen-gray8-smallest` | 47.0 | 47.4 | 1.01× | grey 8-bit | 57 | 1.000 | +| `screen-gray16-store` | 3.715 | 3.770 | 1.01× | grey 16-bit | 4052 | 1.000 | +| `screen-gray16-fastest` | 24.4 | 25.2 | 1.03× | grey 16-bit | 195 | 1.000 | +| `screen-gray16-optimal` | 30.4 | 30.9 | 1.01× | grey 16-bit | 83 | 1.000 | +| `screen-gray16-smallest` | 77.1 | 77.1 | 1.00× | grey 16-bit | 82 | 1.000 | +| `screen-rgb8-store` | 5.496 | 5.795 | 1.05× | RGB 8-bit | 6077 | 1.000 | +| `screen-rgb8-fastest` | 35.7 | 37.1 | 1.04× | RGB 8-bit | 186 | 1.000 | +| `screen-rgb8-optimal` | 41.6 | 43.7 | 1.05× | RGB 8-bit | 78 | 1.000 | +| `screen-rgb8-smallest` | 86.7 | 87.1 | 1.00× | RGB 8-bit | 76 | 1.000 | +| `screen-rgb16-store` | 13.3 | 9.774 | 0.73× | RGB 8-bit | 6077 | 0.500 | +| `screen-rgb16-fastest` | 88.3 | 48.0 | 0.54× | RGB 8-bit | 186 | 0.624 | +| `screen-rgb16-optimal` | 87.3 | 60.1 | 0.69× | RGB 8-bit | 78 | 0.813 | +| `screen-rgb16-smallest` | 138.1 | 93.1 | 0.67× | RGB 8-bit | 76 | 0.849 | +| `screen-rgba8-store` | 7.844 | 7.684 | 0.98× | RGBA 8-bit | 8102 | 1.000 | +| `screen-rgba8-fastest` | 56.6 | 50.1 | 0.89× | RGBA 8-bit | 250 | 1.000 | +| `screen-rgba8-optimal` | 57.3 | 64.6 | 1.13× | RGBA 8-bit | 85 | 1.000 | +| `screen-rgba8-smallest` | 100.2 | 99.6 | 0.99× | RGBA 8-bit | 82 | 1.000 | +| `screen-rgba16-store` | 17.5 | 14.2 | 0.81× | RGBA 8-bit | 8102 | 0.500 | +| `screen-rgba16-fastest` | 93.8 | 51.4 | 0.55× | RGBA 8-bit | 250 | 0.734 | +| `screen-rgba16-optimal` | 104.5 | 59.2 | 0.57× | RGBA 8-bit | 85 | 0.824 | +| `screen-rgba16-smallest` | 247.7 | 139.5 | 0.56× | RGBA 8-bit | 82 | 0.834 | + +Managed bytes allocated per operation, KB (one warm operation on the timing thread). ImageSharp keeps pixel buffers in its own unmanaged pool and libpng allocates natively, so neither shows here: compare working sets with `peakmem`. + +| Case | current | parallel | reduced | streaming | streaming parallel | baseline | ImageSharp | libpng | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| `photo-gray8-store` | 6136.8 | 7410.5 | 6141.1 | 1.2 | 4.1 | 6136.8 | 6142.1 | — | +| `photo-gray8-fastest` | 5347.9 | 5931.2 | 5352.2 | 1.2 | 4.2 | 5347.9 | 5335.9 | — | +| `photo-gray8-optimal` | 5205.3 | 3890.3 | 5209.6 | 1.2 | 4.2 | 5205.3 | 5294.8 | — | +| `photo-gray8-smallest` | 5246.6 | 4034.7 | 5250.9 | 1.2 | 4.3 | 5246.6 | 5294.8 | — | +| `photo-gray16-store` | 12279.6 | 13375.7 | 12282.8 | 1.2 | 7.3 | 12279.6 | 12380.7 | — | +| `photo-gray16-fastest` | 20001.2 | 14994.4 | 20004.5 | 1.2 | 7.3 | 20001.2 | 12084.5 | — | +| `photo-gray16-optimal` | 11719.4 | 11120.4 | 11722.6 | 1.2 | 7.2 | 11719.4 | 12104.0 | — | +| `photo-gray16-smallest` | 11749.1 | 11212.7 | 11752.4 | 1.2 | 7.3 | 11749.1 | 12104.0 | — | +| `photo-rgb8-store` | 22539.9 | 20621.8 | 22545.3 | 1.2 | 7.9 | 22539.9 | 22528.8 | — | +| `photo-rgb8-fastest` | 13350.4 | 22620.3 | 13355.8 | 1.2 | 8.0 | 13350.4 | 11336.3 | — | +| `photo-rgb8-optimal` | 10954.8 | 13611.7 | 10960.2 | 1.2 | 8.0 | 10954.8 | 11037.3 | — | +| `photo-rgb8-smallest` | 10921.0 | 13459.0 | 10926.4 | 1.2 | 7.9 | 10921.0 | 11028.0 | — | +| `photo-rgb16-store` | 45085.9 | 38556.5 | 45089.1 | 1.2 | 7.9 | 45085.9 | 45153.9 | — | +| `photo-rgb16-fastest` | 45733.9 | 40467.1 | 45737.1 | 1.2 | 8.0 | 45733.9 | 44258.2 | — | +| `photo-rgb16-optimal` | 43503.7 | 32354.6 | 43506.9 | 1.2 | 7.9 | 43503.7 | 44384.6 | — | +| `photo-rgb16-smallest` | 43526.1 | 33546.6 | 43529.3 | 1.2 | 8.1 | 43526.1 | 44384.6 | — | +| `photo-rgba8-store` | 24565.2 | 27492.6 | 24570.6 | 1.2 | 7.9 | 24565.2 | 24554.0 | — | +| `photo-rgba8-fastest` | 24470.8 | 16375.7 | 24476.2 | 1.2 | 7.9 | 24470.8 | 11791.3 | — | +| `photo-rgba8-optimal` | 11373.4 | 9551.9 | 11378.8 | 1.2 | 8.0 | 11373.4 | 11491.1 | — | +| `photo-rgba8-smallest` | 11347.4 | 9492.1 | 11352.8 | 1.2 | 8.2 | 11347.4 | 11464.9 | — | +| `photo-rgba16-store` | 49136.5 | 54556.4 | 49139.7 | 1.2 | 7.9 | 49136.5 | 49204.1 | — | +| `photo-rgba16-fastest` | 82652.1 | 53385.8 | 82655.4 | 1.2 | 8.0 | 82652.1 | 47310.9 | — | +| `photo-rgba16-optimal` | 46433.0 | 41661.4 | 46436.2 | 1.2 | 8.1 | 46433.0 | 47467.4 | — | +| `photo-rgba16-smallest` | 46441.0 | 41475.3 | 46444.2 | 1.2 | 8.0 | 46441.0 | 47467.4 | — | +| `screen-gray8-store` | 6136.8 | 7410.2 | 6140.6 | 1.2 | 4.1 | 6136.8 | 6142.1 | — | +| `screen-gray8-fastest` | 370.9 | 511.5 | 374.7 | 1.2 | 4.1 | 370.9 | 346.5 | — | +| `screen-gray8-optimal` | 181.5 | 335.2 | 185.3 | 1.2 | 4.3 | 181.5 | 194.5 | — | +| `screen-gray8-smallest` | 178.5 | 326.8 | 182.4 | 1.2 | 4.2 | 178.5 | 192.7 | — | +| `screen-gray16-store` | 12279.6 | 13375.5 | 12282.8 | 1.2 | 7.3 | 12279.6 | 12380.7 | — | +| `screen-gray16-fastest` | 707.1 | 910.7 | 710.3 | 1.2 | 7.3 | 707.1 | 754.9 | — | +| `screen-gray16-optimal` | 332.9 | 448.2 | 336.2 | 1.2 | 7.4 | 332.9 | 449.4 | — | +| `screen-gray16-smallest` | 331.7 | 579.8 | 335.0 | 1.2 | 7.4 | 331.7 | 446.5 | — | +| `screen-rgb8-store` | 22539.9 | 19282.5 | 22545.3 | 1.2 | 7.8 | 22539.9 | — | — | +| `screen-rgb8-fastest` | 698.6 | 824.6 | 704.0 | 1.2 | 8.2 | 698.6 | — | — | +| `screen-rgb8-optimal` | 328.0 | 613.6 | 333.4 | 1.2 | 8.1 | 328.0 | — | — | +| `screen-rgb8-smallest` | 326.1 | 434.5 | 331.5 | 1.2 | 8.1 | 326.1 | 342.5 | — | +| `screen-rgb16-store` | 45085.9 | 38556.6 | 22545.3 | 1.2 | 7.8 | 45085.9 | 45153.9 | — | +| `screen-rgb16-fastest` | 1322.7 | 1799.3 | 704.0 | 1.2 | 8.1 | 1322.7 | 803.8 | — | +| `screen-rgb16-optimal` | 345.9 | 1082.4 | 333.4 | 1.2 | 8.1 | 345.9 | 466.0 | — | +| `screen-rgb16-smallest` | 339.6 | 1059.0 | 331.5 | 1.2 | 7.9 | 339.6 | 458.1 | — | +| `screen-rgba8-store` | 24565.2 | 27282.7 | 24570.6 | 1.2 | 7.3 | 24565.2 | 24554.0 | — | +| `screen-rgba8-fastest` | 762.9 | 1357.7 | 768.3 | 1.2 | 8.2 | 762.9 | 676.6 | — | +| `screen-rgba8-optimal` | 335.3 | 533.6 | 340.7 | 1.2 | 8.0 | 335.3 | 350.5 | — | +| `screen-rgba8-smallest` | 332.3 | 776.4 | 337.7 | 1.2 | 8.2 | 332.3 | 348.3 | — | +| `screen-rgba16-store` | 49136.5 | 51406.1 | 24570.6 | 1.2 | 7.9 | 49136.5 | 49204.1 | — | +| `screen-rgba16-fastest` | 1365.5 | 2165.6 | 768.3 | 1.2 | 8.1 | 1365.5 | 843.8 | — | +| `screen-rgba16-optimal` | 353.5 | 1305.2 | 340.7 | 1.2 | 8.1 | 353.5 | 475.3 | — | +| `screen-rgba16-smallest` | 348.7 | 1286.1 | 337.7 | 1.2 | 8.1 | 348.7 | 467.7 | — | + +Notes: + +- `screen-rgb8-store`: ImageSharp: output does not round-trip (samples differ), not timed +- `screen-rgb8-fastest`: ImageSharp: output does not round-trip (samples differ), not timed +- `screen-rgb8-optimal`: ImageSharp: output does not round-trip (samples differ), not timed diff --git a/docs/known-gaps.md b/docs/known-gaps.md index bda62f0..7de09e2 100644 --- a/docs/known-gaps.md +++ b/docs/known-gaps.md @@ -46,7 +46,7 @@ HEIF 解码也已调优(M3),基准项目是 `Sdcb.SimdCodecs.Heif.Benchmar ### 门面与公共接口 - **HEIF 要显式注册。** HEVC 有专利负担,`Sdcb.SimdCodecs.Heif` 不在元包里,门面也不引用它;安装后调用一次 `ImageCodecs.Register(HeifImageDecoder.Registration)`,门面的全部入口才会处理 HEIF。注册前 `DetectFormat` 仍报 `ImageFormat.Heif`,但 `IsDecodable` 为 `false`、`Try*` 返回 `false`。注册是进程级的:幂等、线程安全、 不能撤销;注册的编解码器排在内置的之后嗅探。没有反注册、优先级、按名字查找,这是有意保持最小。 -- **编码器抽象(2.0 起)的流式程度不一。** `IImageEncoder` 的会话可以逐行推送像素,但目前每个编码器都在会话里 缓冲整幅图,`Commit` 时一次编码(`BufferedEncoderSession`):契约不变,只是没有内存收益。PNG、BMP、QOI、PNM 天然逐行,以后可以改成真正流式。 +- **编码器抽象(2.0 起)的流式程度不一。** `IImageEncoder` 的会话可以逐行推送像素,但目前除 PNG 外每个编码器都在会话里 缓冲整幅图,`Commit` 时一次编码(`BufferedEncoderSession`):契约不变,只是没有内存收益。PNG 的会话已经真正流式:每批行编码完就把 IDAT 块交给写入器,内存只占一批行(`LosslessReduction`、`Quantize` 要整幅图,多帧 APNG 要 `PngWriteOptions.Animation`,这三种仍缓冲)。BMP、QOI、PNM 天然逐行,以后可以改成真正流式。 - **所有 codec 都接受任意 2 的幂作为 `DecodeOptions.ScaleDenominator`,但只有部分是原生的。** JPEG 原生支持 2、4、8(DCT 域缩放);JPEG 2000 原生支持不超过 2 的分解级数次方的任意 2 的幂(略去高分辨率级别,与 `opj_decompress -r` 一致),但 SIZ 原点不为 0 的图没有原生缩减。超出原生范围的分母先按最大的原生分母解码,再用冻结的 box 滤波缩小(见 [API 设计](api-design.md))。PNG(非隔行)、WebP 有损静态图和 HEIF(tile 边界与 box 对齐时)边解码边缩小,不持有整帧,峰值内存约为输出加几行,但每个像素仍要解码,耗时与整幅解码相近。其他 codec 整幅解码后再缩小,结果相同,没有加速。`TryGetClosestSize` 只报告原生尺寸(JPEG、JPEG 2000 之外报告原尺寸)。 - **区域解码只在部分格式上按需。** `DecodeOptions.Region` 对所有 codec 都可用,按需读取的有:HEIF(只解码与区域相交的网格 tile,只转换区域内的像素)、TIFF(只读与区域相交的条带或分块)、JPEG、PNG(非隔行)和 WebP 有损静态图;其他格式是整幅解码后裁剪,语义一致,没有性能收益。JPEG 只持有 MCU 行条带和区域本身,只对区域内的行做上采样和色彩转换,所以超过 2 GB 的大图也能取区域;但每个 MCU 仍要熵解码和 IDCT(baseline 码流没有可跳转的索引),耗时接近整幅解码,按 restart 间隔跳过熵解码留给 2.x。PNG 和 WebP 解到区域需要的最后一行就停:区域上方的行仍要解压,区域下方的数据不读也不校验,所以一个文件取区域成功、整幅解码却可能失败。 - **整幅输出受单个数组 2 GB 上限约束。** 输出光栅超过 `Array.MaxLength` 字节时,`TryDecode` 返回 false, `ImageDecoder` 的 `Decode` 抛出 `InvalidDataException` 并提示改用缩放或区域解码;`RasterImage` 的工厂方法抛出 `ArgumentOutOfRangeException`。JPEG progressive 或分多次扫描的帧要整帧保存系数,总样本数上限为 `int.MaxValue`, 缩放解码也不例外。 diff --git a/src/Sdcb.SimdCodecs.Png/PngImageEncoder.cs b/src/Sdcb.SimdCodecs.Png/PngImageEncoder.cs index 78438f2..59187ea 100644 --- a/src/Sdcb.SimdCodecs.Png/PngImageEncoder.cs +++ b/src/Sdcb.SimdCodecs.Png/PngImageEncoder.cs @@ -14,8 +14,20 @@ namespace Sdcb.SimdCodecs.Png; /// and an XMP iTXt chunk, and a non-sRGB a cICP chunk. /// /// The output is exactly the file writes for the converted pixels and the -/// given (a still format: one frame). PNG needs the whole image for its filter pass and -/// deflate stream, so the session collects the rows (). +/// given, packaged in IDAT chunks of 64 KiB (see below). +/// +/// +/// Streaming. By default a session holds one frame and streams it (): +/// the header goes out at AddFrame, each band of rows is filtered and deflated as it arrives and leaves as complete +/// IDAT chunks, and memory is a band of rows. The zlib stream is the one writes; it is +/// split into 64 KiB IDAT chunks (12 bytes each) where writes one, so a file whose zlib +/// stream fits 64 KiB is 's byte for byte. With +/// each band is one of 's fragments, compressed in parallel, up to 2 MiB of rows a fragment; an +/// image whose fragments would be larger is cut into 2 MiB bands instead, so its zlib stream has more fragments than +/// 's (the pixels never differ). Memory is then min(ParallelFragments, ProcessorCount) bands. and +/// pick the layout from the whole image, and takes several frames (an APNG); with +/// any of them the session collects the frames and writes 's (or 's) +/// file at Commit, false. /// /// public sealed class PngImageEncoder : IImageEncoder @@ -39,15 +51,23 @@ public sealed class PngImageEncoder : IImageEncoder /// is a (null means the defaults; any other type /// throws ). Metadata and colour given to override the matching /// options. - 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 PngWriteOptions(), - PngWriteOptions o => o, + PngWriteOptions p => p, _ => throw new ArgumentException($"PNG encoding takes PngWriteOptions, not {options.GetType().Name}.", nameof(options)), - }); + }; + return Streams(o) ? new PngStreamingSession(output, o) : new Session(output, o); + } + + /// Whether a session with streams: all but an animation and the two options that + /// pick the layout from the whole image. + internal static bool Streams(PngWriteOptions options) => + !options.Animation && !options.LosslessReduction && options.Quantize is null; - private static PixelFormat Native(PixelFormat f) => f.Layout switch + internal static PixelFormat Native(PixelFormat f) => f.Layout switch { ChannelLayout.Rgba or ChannelLayout.Bgra => new PixelFormat(ChannelLayout.Rgba, f.Sample), ChannelLayout.Rgb or ChannelLayout.Bgr => new PixelFormat(ChannelLayout.Rgb, f.Sample), @@ -57,7 +77,8 @@ public static IImageEncoderSession Create(IBufferWriter output, EncodeOpti private sealed class Session(IBufferWriter output, PngWriteOptions options) : BufferedEncoderSession(output) { - public override int MaxFrames => int.MaxValue; + // Several frames are an APNG, which the caller asks for: every option set holds the same number of frames. + public override int MaxFrames => options.Animation ? int.MaxValue : 1; protected override void Encode(IReadOnlyList frames, CancellationToken cancellationToken) { @@ -70,7 +91,7 @@ protected override void Encode(IReadOnlyList frames, Cancellation var frame = frames[0]; var native = Native(frame.Format); var pixels = frame.PixelsAs(native); - var o = WithFrame(options, frame); + var o = WithFrame(options, frame.Metadata, frame.Color); int w = frame.Width, h = frame.Height; byte[] file = native.Sample == SampleFormat.UInt16 ? native.Layout switch @@ -96,7 +117,7 @@ private void EncodeAnimation(IReadOnlyList frames, CancellationTo { var first = frames[0]; var wide = frames.Any(f => f.Format.Sample == SampleFormat.UInt16); - var encoder = new PngAnimationEncoder(first.Width, first.Height, WithFrame(options, first), wide); + var encoder = new PngAnimationEncoder(first.Width, first.Height, WithFrame(options, first.Metadata, first.Color), wide); for (var i = 0; i < frames.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); @@ -107,26 +128,26 @@ private void EncodeAnimation(IReadOnlyList frames, CancellationTo } WriteOutput(encoder.Encode()); } + } - // The frame's metadata and colour override the options': ICC, Exif, an XMP iTXt, cICP. - private static PngWriteOptions WithFrame(PngWriteOptions options, BufferedFrame frame) + // The frame's metadata and colour override the options': ICC, Exif, an XMP iTXt, cICP. + internal static PngWriteOptions WithFrame(PngWriteOptions options, ImageMetadata? metadata, ColorEncoding? color) + { + var o = options; + if (metadata is { } m) { - var o = options; - if (frame.Metadata is { } m) + if (!m.Icc.IsEmpty) + o = o with { IccProfile = m.Icc.ToArray() }; + if (!m.Exif.IsEmpty) + o = o with { Exif = m.Exif.ToArray() }; + if (!m.Xmp.IsEmpty) { - if (!m.Icc.IsEmpty) - o = o with { IccProfile = m.Icc.ToArray() }; - if (!m.Exif.IsEmpty) - o = o with { Exif = m.Exif.ToArray() }; - if (!m.Xmp.IsEmpty) - { - var text = new List(o.Text ?? []) { new("XML:com.adobe.xmp", Encoding.UTF8.GetString(m.Xmp.Span)) }; - o = o with { Text = text }; - } + var text = new List(o.Text ?? []) { new("XML:com.adobe.xmp", Encoding.UTF8.GetString(m.Xmp.Span)) }; + o = o with { Text = text }; } - if (frame.Color is { } c && c != ColorEncoding.AssumedSrgb && o.Cicp is null) - o = o with { Cicp = new CicpChunk(c.Primaries, c.Transfer, MatrixCoefficients.Identity, c.FullRange) }; - return o; } + if (color is { } c && c != ColorEncoding.AssumedSrgb && o.Cicp is null) + o = o with { Cicp = new CicpChunk(c.Primaries, c.Transfer, MatrixCoefficients.Identity, c.FullRange) }; + return o; } } diff --git a/src/Sdcb.SimdCodecs.Png/PngStreamingSession.cs b/src/Sdcb.SimdCodecs.Png/PngStreamingSession.cs new file mode 100644 index 0000000..2674413 --- /dev/null +++ b/src/Sdcb.SimdCodecs.Png/PngStreamingSession.cs @@ -0,0 +1,446 @@ +using System.Buffers; +using System.IO.Compression; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs.Png; + +/// +/// The streaming session: one still frame, written as its rows arrive. The signature, IHDR +/// and every chunk before the image data go out at AddFrame; the rows are filtered and deflated a band at a time +/// and leave as complete IDAT chunks of ; the trailing chunks and IEND at +/// Commit. Memory is a band of rows, never the image. +/// +/// Bytes. With at 1 (the default) the zlib stream is exactly the +/// one writes, since the row filter and the deflate calls see the same rows in the same order; +/// only its packaging differs: writes one IDAT, whose length it back-patches, and this +/// session one per of zlib stream (12 bytes each). A file whose zlib stream fits one chunk is +/// the buffered file byte for byte. With parallel fragments each band is one of 's fragments, so +/// the zlib stream is again the buffered one, as long as a fragment holds at most +/// of filtered rows; a larger image is cut into bands of that size instead, more +/// fragments than makes, so its bytes differ (the pixels never do). At most +/// min(ParallelFragments, ProcessorCount) bands are compressed at once, which bounds the memory. +/// +/// +/// Band boundaries are fixed by the image's size and the options, never by how the caller splits its +/// WriteRows calls, so the file is the same whether the rows come one at a time or all at once. +/// +/// +/// A WriteRows whose token is already cancelled consumes nothing. One cancelled while it runs (checked at each +/// band) or failing part-way has written part of the image, and the session refuses everything after it but +/// Dispose. +/// +/// +internal sealed class PngStreamingSession(IBufferWriter output, PngWriteOptions options) : StreamingEncoderSession(output) +{ + /// The zlib bytes each IDAT carries (the last one carries the rest). + internal const int IdatChunkBytes = 64 * 1024; + + /// Filtered-row bytes per band in the single-stream path: what the rows are gathered into before filtering. + private const int SerialBandBytes = 128 * 1024; + + /// + /// The most filtered-row bytes an independently deflated band holds in the parallel path: a band is + /// 's fragment when that is smaller, so the two write the same zlib stream. + /// + internal const int MaxFragmentPayloadBytes = 2 * 1024 * 1024; + + private readonly PngWriteOptions _given = options; + private PngWriteOptions _options = options; // the frame's: AddFrame merges its metadata into _given + private PngEncodePlan? _plan; + private PixelFormat _format, _native; + private int _width, _height, _sourceRowBytes, _payloadRowBytes; + private IdatWriter? _idat; + private ZLibStream? _zlib; // the single-stream path + private Fragments? _parallel; // the fragmented path + private Band? _band; // the rows being gathered + private int _bandFirstRow; // image row of the band's first row + private bool _faulted; + + public override int MaxFrames => 1; + + protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) + { + // Everything that can refuse the frame runs before the first byte reaches the output, and nothing of the session + // changes until it has: a refused AddFrame leaves the session as it was. + var o = PngImageEncoder.WithFrame(_given, metadata, color); + PngWriter.ValidateText(o); + if (!Enum.IsDefined(o.CompressionLevel)) + throw new ArgumentOutOfRangeException(nameof(PngWriteOptions.CompressionLevel), o.CompressionLevel, "Not a CompressionLevel."); + var native = PngImageEncoder.Native(format); + var sampleBytes = native.Sample == SampleFormat.UInt16 ? 2 : 1; + var srcChannels = native.Layout switch + { + ChannelLayout.Rgba => 4, + ChannelLayout.Rgb => 3, + ChannelLayout.GrayAlpha => 2, + _ => 1, + }; + var dstChannels = o.DiscardAlpha && srcChannels is 2 or 4 ? srcChannels - 1 : srcChannels; + var plan = PngEncodePlan.Direct(dstChannels, srcChannels, sampleBytes, o.TransparentColor); + var sourceRowBytes = plan.SourceRowBytes(width); + var payloadRowBytes = checked(plan.RowBytes(width) + 1); + using var head = new MemoryStream(); + head.Write(PngWriter.Signature); + PngWriter.WritePreImageChunks(head, width, height, plan, o); + + _options = o; + _plan = plan; + _native = native; + _format = format; + _width = width; + _height = height; + _sourceRowBytes = sourceRowBytes; + _payloadRowBytes = payloadRowBytes; + WriteOutput(head.GetBuffer().AsSpan(0, (int)head.Length)); + + _idat = new IdatWriter(Output); + var fragments = PngWriter.EffectiveFragmentCount(o.ParallelFragments, height, payloadRowBytes - 1); + var parallel = fragments > 1; + var bandRows = parallel + ? Math.Min((height + fragments - 1) / fragments, Math.Max(2, MaxFragmentPayloadBytes / payloadRowBytes)) + : Math.Min(height, Math.Max(1, SerialBandBytes / payloadRowBytes)); + if (parallel) + { + _parallel = new Fragments(Math.Max(1, Math.Min(o.ParallelFragments, Environment.ProcessorCount)), bandRows, sourceRowBytes); + PngWriter.WriteZlibHeader(_idat, o.CompressionLevel); + _band = _parallel.Take(); + } + else + { + _zlib = new ZLibStream(_idat, o.CompressionLevel, leaveOpen: true); + _band = new Band(bandRows, sourceRowBytes); + } + } + + protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_band is null, this); + if (_faulted) + throw new InvalidOperationException("An earlier failure left the session unusable."); + try + { + var inRowBytes = _width * _format.BytesPerPixel; + var band = _band; + for (var y = 0; y < rowCount; y++) + { + var source = rows.Slice(y * stride, inRowBytes); + var destination = band.Row(band.Count); + if (_format == _native) + source.CopyTo(destination); + else + PixelConverter.ConvertRow(source, _format, destination, _native, _width); + band.Count++; + if (band.Count == band.Capacity) + { + cancellationToken.ThrowIfCancellationRequested(); + band = FlushBand(); + } + } + } + catch + { + _faulted = true; + throw; + } + } + + protected override void EndFrame(CancellationToken cancellationToken) + { + try + { + if (_band!.Count > 0) + FlushBand(); + if (_parallel is { } parallel) + { + parallel.DrainAll(_idat!); + // A final empty fixed-Huffman block, then the Adler-32 of every band, as PngWriter's fragmented stream ends. + Span tail = stackalloc byte[6]; + tail[0] = 0x03; + tail[1] = 0x00; + PngWriter.WriteBE(tail[2..], parallel.Adler); + _idat!.Write(tail); + } + else + { + _zlib!.Dispose(); // the final block and the Adler-32 + _zlib = null; + } + _idat!.Complete(); + } + catch + { + _faulted = true; + throw; + } + } + + protected override void Finish(CancellationToken cancellationToken) + { + if (_faulted) + throw new InvalidOperationException("An earlier failure left the session unusable."); + using var tail = new MemoryStream(); + PngWriter.WritePostImageChunks(tail, _options); + WriteOutput(tail.GetBuffer().AsSpan(0, (int)tail.Length)); + } + + /// + /// Filters and deflates the gathered band (serially, or hands it to a worker) and returns the band the next rows go + /// into, whose row above is the last row of this one. + /// + private Band FlushBand() + { + var band = _band!; + var first = _bandFirstRow == 0; + if (_parallel is { } parallel) + { + var next = parallel.Take(); + band.Row(band.Count - 1).CopyTo(next.Row(-1)); + parallel.Submit(band, first, _width, _plan!, _options.CompressionLevel, _payloadRowBytes, _idat!); + _band = next; + } + else + { + PngWriter.CompressRows(_zlib!, band.Samples(first, band.Count), first ? 0 : 1, band.Count, _width, _plan!, + _options.CompressionLevel, checksum: false); + band.Row(band.Count - 1).CopyTo(band.Row(-1)); + } + _bandFirstRow += band.Count; + if (_parallel is null) + band.Count = 0; // a submitted band is reset when it is taken again + return _band!; + } + + protected override void Dispose(bool disposing) + { + if (!disposing) + return; + _idat?.Abandon(); // nothing more reaches the output, whatever is disposed below + _parallel?.Dispose(); // waits for the workers before their memory goes back to the pool + _parallel = null; + try + { + _zlib?.Dispose(); + } + catch (Exception) + { + // An abandoned stream: its last bytes have nowhere to go. + } + _zlib = null; + if (_band is { Pooled: false }) + _band.Release(); + _band = null; + _idat?.Release(); + _idat = null; + } + + /// + /// A band of source rows in the native layout, with the row above it in front: row -1 is the last row of the + /// previous band (unused for the image's first band, whose row above is zeros). + /// + private sealed class Band(int capacity, int rowBytes) + { + private byte[]? _rows = ArrayPool.Shared.Rent(checked((capacity + 1) * rowBytes)); + + public int Capacity => capacity; + + public int Count { get; set; } + + /// Owned by a , which returns the memory. + public bool Pooled => Owner is not null; + + /// The fragment job this band belongs to, in the fragmented path. + public object? Owner { get; set; } + + public Span Row(int index) => _rows.AsSpan((index + 1) * rowBytes, rowBytes); + + /// What reads: from row 0 for the image's first band (firstRow 0), + /// else from row -1 (firstRow 1). + public ReadOnlySpan Samples(bool first, int count) => + first ? _rows.AsSpan(rowBytes, count * rowBytes) : _rows.AsSpan(0, (count + 1) * rowBytes); + + public void Release() + { + if (_rows is not null) + ArrayPool.Shared.Return(_rows); + _rows = null; + } + } + + /// + /// The fragmented path: each full band is filtered and deflated on a worker into an independent, sync-flushed deflate + /// fragment, as 's parallel fragments are, and the fragments reach the output in band order. + /// At most limit bands are compressed at once; the caller waits for the oldest when that many are. + /// + private sealed class Fragments(int limit, int bandRows, int sourceRowBytes) : IDisposable + { + private readonly Queue _running = new(); + private readonly Stack _idle = new(); + private readonly List _all = []; + private bool _started; + + /// The Adler-32 of every band emitted so far. + public uint Adler { get; private set; } = 1; + + /// A free band (and its output buffer) for the next rows. + public Band Take() + { + if (!_idle.TryPop(out var job)) + { + job = new Job(new Band(bandRows, sourceRowBytes)); + _all.Add(job); + } + job.Band.Count = 0; + return job.Band; + } + + public void Submit(Band band, bool first, int width, PngEncodePlan plan, CompressionLevel level, int payloadRowBytes, + IdatWriter idat) + { + var job = (Job)band.Owner!; + job.First = first; + job.Rows = band.Count; + job.Payload = (long)band.Count * payloadRowBytes; + job.Work = Task.Run(() => job.Compress(width, plan, level)); + _running.Enqueue(job); + while (_running.Count > 0 && (_running.Count >= limit || _running.Peek().Work!.IsCompleted)) + Emit(idat); + } + + public void DrainAll(IdatWriter idat) + { + while (_running.Count > 0) + Emit(idat); + } + + private void Emit(IdatWriter idat) + { + var job = _running.Dequeue(); + job.Work!.GetAwaiter().GetResult(); + job.Work = null; + idat.Write(job.Output.GetBuffer().AsSpan(0, job.Length)); + Adler = _started ? PngWriter.AdlerCombine(Adler, job.Checksum, job.Payload) : job.Checksum; + _started = true; + _idle.Push(job); + } + + public void Dispose() + { + foreach (var job in _all) + { + try + { + job.Work?.GetAwaiter().GetResult(); + } + catch (Exception) + { + // Already reported to the caller, or the session is abandoned. + } + job.Band.Release(); + } + _all.Clear(); + _running.Clear(); + _idle.Clear(); + } + + private sealed class Job + { + public Job(Band band) + { + Band = band; + band.Owner = this; + } + + public Band Band { get; } + public MemoryStream Output { get; } = new(); + public Task? Work { get; set; } + public bool First { get; set; } + public int Rows { get; set; } + public long Payload { get; set; } + public int Length { get; private set; } + public uint Checksum { get; private set; } + + public void Compress(int width, PngEncodePlan plan, CompressionLevel level) + { + Output.SetLength(0); + var deflate = new DeflateStream(Output, level, leaveOpen: true); + Checksum = PngWriter.CompressRows(deflate, Band.Samples(First, Rows), First ? 0 : 1, Rows, width, plan, level, checksum: true); + deflate.Flush(); // a sync flush: byte-aligned, not final + Length = checked((int)Output.Length); // before Dispose appends a final block + deflate.Dispose(); + } + } + } + + /// + /// The sink the zlib stream is written into: it cuts the stream into IDAT chunks of + /// and hands each to the output as soon as it is full. + /// + internal sealed class IdatWriter(IBufferWriter output) : Stream + { + private byte[]? _chunk = ArrayPool.Shared.Rent(IdatChunkBytes); + private int _count; + private bool _abandoned; + + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void WriteByte(byte value) => Write([value]); + + public override void Write(ReadOnlySpan buffer) + { + if (_abandoned) + return; + ObjectDisposedException.ThrowIf(_chunk is null, this); + while (!buffer.IsEmpty) + { + var n = Math.Min(buffer.Length, IdatChunkBytes - _count); + buffer[..n].CopyTo(_chunk.AsSpan(_count)); + _count += n; + buffer = buffer[n..]; + if (_count == IdatChunkBytes) + Emit(); + } + } + + /// Writes the last, partial chunk. + public void Complete() + { + if (_count > 0) + Emit(); + } + + /// Drops everything written from now on: the session is being disposed unfinished. + public void Abandon() => _abandoned = true; + + public void Release() + { + if (_chunk is not null) + ArrayPool.Shared.Return(_chunk); + _chunk = null; + } + + private void Emit() + { + var data = _chunk.AsSpan(0, _count); + var span = output.GetSpan(_count + 12); + PngWriter.WriteBE(span, (uint)_count); + "IDAT"u8.CopyTo(span[4..]); + data.CopyTo(span[8..]); + PngWriter.WriteBE(span[(8 + _count)..], PngCrc32.Compute("IDAT"u8, data)); + output.Advance(_count + 12); + _count = 0; + } + + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } +} diff --git a/src/Sdcb.SimdCodecs.Png/PngWriteOptions.cs b/src/Sdcb.SimdCodecs.Png/PngWriteOptions.cs index f56a8f0..d1834d0 100644 --- a/src/Sdcb.SimdCodecs.Png/PngWriteOptions.cs +++ b/src/Sdcb.SimdCodecs.Png/PngWriteOptions.cs @@ -184,4 +184,13 @@ public sealed record PngWriteOptions : Sdcb.SimdCodecs.Abstractions.EncodeOption /// num_plays of the acTL chunk. 0 (the default) is forever. Ignored for a still image. /// public int LoopCount { get; init; } + + /// + /// For a session: take several frames and write them as an animated PNG. The session then + /// collects whole frames and writes the file at Commit (IsStreaming false), since an APNG's frame count + /// precedes its first image data. Off by default: the session holds one frame and, unless + /// or needs the whole image, streams it, writing image data as + /// the rows arrive. Ignored by and . + /// + public bool Animation { get; init; } } diff --git a/src/Sdcb.SimdCodecs.Png/PngWriter.cs b/src/Sdcb.SimdCodecs.Png/PngWriter.cs index 1368b63..4bc0d2c 100644 --- a/src/Sdcb.SimdCodecs.Png/PngWriter.cs +++ b/src/Sdcb.SimdCodecs.Png/PngWriter.cs @@ -501,7 +501,7 @@ internal static void WriteImageDataChunk(MemoryStream ms, ReadOnlySpan typ /// so that every fragment holds at least two rows and at least /// . /// - private static int EffectiveFragmentCount(int requested, int height, int stride) + internal static int EffectiveFragmentCount(int requested, int height, int stride) { if (requested <= 1) { @@ -702,7 +702,7 @@ private static unsafe void WriteFragmentedZlibStream(MemoryStream ms, ReadOnlySp /// The two-byte zlib header: deflate with a 32K window, the level's own FLEVEL hint, and the /// FCHECK bits that make the pair divisible by 31 (RFC 1950 s2.2). /// - private static void WriteZlibHeader(Stream destination, CompressionLevel level) + internal static void WriteZlibHeader(Stream destination, CompressionLevel level) { const int Cmf = 0x78; // compression method 8 (deflate), window 32K var flevel = level switch @@ -749,7 +749,7 @@ private static void AdlerUpdate(ref uint a, ref uint b, ReadOnlySpan data) /// checksums and the length of the second. This is what lets fragments be checksummed on the /// threads that produced them instead of in a serial pass over the whole payload afterwards. /// - private static uint AdlerCombine(uint first, uint second, long secondLength) + internal static uint AdlerCombine(uint first, uint second, long secondLength) { const uint Base = 65521; diff --git a/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt index 7dc5c58..0e41651 100644 --- a/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +Sdcb.SimdCodecs.Png.PngWriteOptions.Animation.get -> bool +Sdcb.SimdCodecs.Png.PngWriteOptions.Animation.init -> void diff --git a/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs b/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs index f80139a..c5ccb33 100644 --- a/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs +++ b/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs @@ -86,7 +86,7 @@ private static int V2() // Several frames to the PNG encoder through the session: an APNG, opened again through the facade. var apng = new System.Buffers.ArrayBufferWriter(); - using (var animation = ImageCodecs.CreateEncoder(ImageFormat.Png, apng, new PngWriteOptions { LoopCount = 3 })) + using (var animation = ImageCodecs.CreateEncoder(ImageFormat.Png, apng, new PngWriteOptions { LoopCount = 3, Animation = true })) { for (var f = 0; f < 3; f++) { diff --git a/tests/Sdcb.SimdCodecs.Tests/PngApngEncoderTests.cs b/tests/Sdcb.SimdCodecs.Tests/PngApngEncoderTests.cs index 9a768cd..151fe0b 100644 --- a/tests/Sdcb.SimdCodecs.Tests/PngApngEncoderTests.cs +++ b/tests/Sdcb.SimdCodecs.Tests/PngApngEncoderTests.cs @@ -363,7 +363,7 @@ public void ASessionOfSeveralFramesWritesAnApngWithTheirDurations() { var input = PngApngOracleTests.Sequence(W, H, 4, false); var file = Session([.. input.Select((f, i) => (f, PixelFormat.Rgba32, (TimeSpan?)TimeSpan.FromMilliseconds(30 + 10 * i)))], - new PngWriteOptions { LoopCount = 2 }); + new PngWriteOptions { LoopCount = 2, Animation = true }); ImageCodecs.DetectFormat(file).ShouldBe(ImageFormat.Png); ImageCodecs.TryOpenFrames(file, out var reader).ShouldBeTrue(); using (reader) @@ -394,7 +394,7 @@ public void ASessionTakesFramesInDifferentFormatsAndOneSixteenBitFrameMakesTheAn var opaque0 = (byte[])a[0].Clone(); for (var i = 0; i < W * H; i++) opaque0[i * 4 + 3] = 255; var wideFrame = Wide(a[1]); - var file = Session([(rgb, PixelFormat.Rgb24, null), (wideFrame, PixelFormat.Rgba64, null)]); + var file = Session([(rgb, PixelFormat.Rgb24, null), (wideFrame, PixelFormat.Rgba64, null)], new PngWriteOptions { Animation = true }); var decoder = new PngAnimationDecoder(file); decoder.BitDepth.ShouldBe(16); decoder.FrameCount.ShouldBe(2); @@ -419,7 +419,7 @@ public void ASessionOfOneFrameIsTheStillPngByteForByte() public void ASessionWhoseFramesDifferInSizeIsRefused() { var writer = new ArrayBufferWriter(); - using var session = ImageCodecs.CreateEncoder(ImageFormat.Png, writer); + using var session = ImageCodecs.CreateEncoder(ImageFormat.Png, writer, new PngWriteOptions { Animation = true }); session.AddFrame(4, 4, PixelFormat.Rgba32).WriteRows(new byte[64], 4, 0, TestContext.Current.CancellationToken); session.AddFrame(5, 4, PixelFormat.Rgba32).WriteRows(new byte[80], 4, 0, TestContext.Current.CancellationToken); Should.Throw(() => session.Commit(TestContext.Current.CancellationToken)); diff --git a/tests/Sdcb.SimdCodecs.Tests/PngStreamingEncodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/PngStreamingEncodeTests.cs new file mode 100644 index 0000000..bbbd342 --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/PngStreamingEncodeTests.cs @@ -0,0 +1,437 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Png; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// The streaming session: bytes leave as the rows arrive, the file decodes (ours and +/// libpng through Magick.NET) to exactly the input, the bytes do not depend on how the rows were split, the options that +/// need the whole image fall back to the buffered session's unchanged bytes, and memory is a band of rows. +/// +public sealed class PngStreamingEncodeTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// + /// A column pattern plus a row pattern plus a little noise: every filter wins somewhere (Paeth predicts the sum + /// exactly, Up wins where the row pattern is flat, Sub where the column pattern is), so a band that filtered against + /// the wrong row above would decode wrong. Compressible enough to be quick, noisy enough to fill IDATs. + /// + private static byte[] Photo(int width, int height, PixelFormat format, int seed) + { + var bpp = format.BytesPerPixel; + var pixels = new byte[(long)width * height * bpp]; + var random = new Random(seed); + var columns = new byte[width * bpp]; + random.NextBytes(columns); + var rows = new byte[height]; + random.NextBytes(rows); + for (var y = 0; y < height; y++) + { + var flatColumns = y / 64 % 3 == 1; + var flatRows = y / 64 % 3 == 2; + for (var x = 0; x < width; x++) + { + var at = ((long)y * width + x) * bpp; + for (var b = 0; b < bpp; b++) + pixels[at + b] = (byte)((flatColumns ? x : columns[x * bpp + b]) + (flatRows ? 0 : rows[y]) + random.Next(4)); + } + } + return pixels; + } + + private static byte[] Encode(byte[] pixels, int width, int height, PixelFormat format, PngWriteOptions? options, + Func? band = null, int seed = 1, bool expectStreaming = true) + { + var output = new ArrayBufferWriter(); + using var session = PngImageEncoder.Create(output, options); + session.IsStreaming.ShouldBe(expectStreaming); + var frame = session.AddFrame(width, height, format); + var rowBytes = width * format.BytesPerPixel; + var random = new Random(seed); + while (frame.RowsWritten < height) + { + var n = Math.Min(band?.Invoke(random.Next()) ?? height, height - frame.RowsWritten); + frame.WriteRows(pixels.AsSpan(frame.RowsWritten * rowBytes, n * rowBytes), n, 0, Ct); + } + session.Commit(Ct); + return output.WrittenSpan.ToArray(); + } + + /// What the file holds: the input in the encoder's native layout (BGR reordered, alpha unpremultiplied). + private static (byte[] Pixels, PixelFormat Format) Expected(byte[] pixels, int width, int height, PixelFormat format) + { + var native = PngImageEncoder.GetClosestInputFormat(format); + return (PixelConverter.ToPacked(pixels, 0, format, native, width, height), native); + } + + private static byte[] DecodeOurs(byte[] file, int width, int height, PixelFormat format) + { + var pixels = new byte[(long)width * height * format.BytesPerPixel]; + PngImageDecoder.Registration.TryDecodeInto(file, pixels, width * format.BytesPerPixel, format, null, Ct).ShouldBeTrue(); + return pixels; + } + + /// libpng's reading of the file, as 16-bit samples in the file's channel order. + private static ushort[] DecodeMagick(byte[] file, int width, int height, int channels) + { + using var image = new MagickImage(file); + ((int)image.Width, (int)image.Height).ShouldBe((width, height)); + using var pixels = image.GetPixels(); + var map = channels switch { 1 => "R", 2 => "RA", 3 => "RGB", _ => "RGBA" }; + return pixels.ToShortArray(0, 0, (uint)width, (uint)height, map)!; + } + + private static ushort[] AsSixteenBit(byte[] native, PixelFormat format) => format.Sample == SampleFormat.UInt16 + ? System.Runtime.InteropServices.MemoryMarshal.Cast(native).ToArray() + : [.. native.Select(v => (ushort)(v * 257))]; + + private static int Channels(PixelFormat native) => native.Layout switch + { + ChannelLayout.Rgba => 4, + ChannelLayout.Rgb => 3, + ChannelLayout.GrayAlpha => 2, + _ => 1, + }; + + public static TheoryData FormatIndices() + { + var data = new TheoryData(); + for (var i = 0; i < PixelFormat.All.Length; i++) + data.Add(i); + return data; + } + + [Theory] + [MemberData(nameof(FormatIndices))] + public void EveryInputFormatDecodesToExactlyItsPixels(int formatIndex) + { + var format = PixelFormat.All[formatIndex]; + const int w = 97, h = 61; + var pixels = Photo(w, h, format, formatIndex); + var (expected, native) = Expected(pixels, w, h, format); + foreach (var options in new PngWriteOptions?[] { null, new() { CompressionLevel = CompressionLevel.NoCompression }, new() { ParallelFragments = 4 } }) + { + var file = Encode(pixels, w, h, format, options, band: r => 1 + r % 9); + DecodeOurs(file, w, h, native).ShouldBe(expected, $"{format} {options}: ours"); + DecodeMagick(file, w, h, Channels(native)).ShouldBe(AsSixteenBit(expected, native), $"{format} {options}: libpng"); + } + } + + [Theory] + [MemberData(nameof(FormatIndices))] + public void EveryInputFormatStreamsAcrossManyIdatsAndParallelBands(int formatIndex) + { + var format = PixelFormat.All[formatIndex]; + const int w = 1031, h = 700; // 16-bit RGBA: 5.8 MB of payload, two parallel bands; several IDATs everywhere + var pixels = Photo(w, h, format, formatIndex + 100); + var (expected, native) = Expected(pixels, w, h, format); + foreach (var options in new PngWriteOptions?[] { null, new() { ParallelFragments = 3, CompressionLevel = CompressionLevel.Fastest } }) + { + var file = Encode(pixels, w, h, format, options, band: r => 1 + r % 50); + Idats(file).Count.ShouldBeGreaterThan(1, $"{format} {options}"); + DecodeOurs(file, w, h, native).ShouldBe(expected, $"{format} {options}: ours"); + DecodeMagick(file, w, h, Channels(native)).ShouldBe(AsSixteenBit(expected, native), $"{format} {options}: libpng"); + } + } + + [Fact] + public void DiscardAlphaAndTransparentColourStream() + { + const int w = 50, h = 31; + var rgba = Photo(w, h, PixelFormat.Rgba64, 3); + var file = Encode(rgba, w, h, PixelFormat.Rgba64, new PngWriteOptions { DiscardAlpha = true }, band: _ => 4); + file.ShouldBe(PngWriter.EncodeRgba16(System.Runtime.InteropServices.MemoryMarshal.Cast(rgba), w, h, + new PngWriteOptions { DiscardAlpha = true })); + var rgb = Photo(w, h, PixelFormat.Rgb24, 4); + var keyed = new PngWriteOptions { TransparentColor = [1, 2, 3], Gamma = 0.45455, Text = [new PngText("Title", "streamed")] }; + Encode(rgb, w, h, PixelFormat.Rgb24, keyed, band: _ => 7).ShouldBe(PngWriter.EncodeRgb8(rgb, w, h, keyed)); + } + + [Fact] + public void ASmallFileIsTheBufferedFileByteForByte() + { + const int w = 64, h = 48; + var pixels = Photo(w, h, PixelFormat.Rgba32, 9); + var options = new PngWriteOptions + { + Exif = [0x49, 0x49, 0x2A, 0, 8, 0, 0, 0, 0, 0], PhysicalDimensions = PngPhysicalDimensions.FromDpi(96), + Cicp = CicpChunk.Srgb, Text = [new PngText("Comment", new string('x', 3000))], + }; + Encode(pixels, w, h, PixelFormat.Rgba32, options, band: _ => 5).ShouldBe(PngWriter.Encode(pixels, w, h, options)); + Encode(pixels, w, h, PixelFormat.Rgba32, null).ShouldBe(PngWriter.Encode(pixels, w, h)); + } + + [Fact] + public void ALargeFileHasTheBufferedZlibStreamInFixedSizeIdats() + { + const int w = 900, h = 600; + var pixels = Photo(w, h, PixelFormat.Rgb24, 11); + var streamed = Encode(pixels, w, h, PixelFormat.Rgb24, null, band: r => 1 + r % 13); + var buffered = PngWriter.EncodeRgb8(pixels, w, h); + var idats = Idats(streamed); + idats.Count.ShouldBeGreaterThan(2); + idats.SkipLast(1).ShouldAllBe(c => c.Length == PngStreamingSession.IdatChunkBytes); + Idats(buffered).Count.ShouldBe(1); + idats.SelectMany(c => c).ToArray().ShouldBe(Idats(buffered)[0]); + streamed.Length.ShouldBe(buffered.Length + 12 * (idats.Count - 1)); + } + + [Fact] + public void ParallelBandsAreTheBufferedFragmentsUpToTheCap() + { + // 6 fragments of 117 rows x 3601 bytes: under the cap, so the zlib stream is PngWriter's. + const int w = 1200, h = 700; + var pixels = Photo(w, h, PixelFormat.Rgb24, 14); + var options = new PngWriteOptions { ParallelFragments = 6 }; + var streamed = Encode(pixels, w, h, PixelFormat.Rgb24, options, band: r => 1 + r % 40); + Idats(streamed).SelectMany(c => c).ToArray().ShouldBe(Idats(PngWriter.EncodeRgb8(pixels, w, h, options))[0]); + + // 2 fragments of 1500 rows x 4097 bytes: over the cap, so bands of 511 rows, and other bytes for the same pixels. + const int tall = 3000, wide = 1024; + var more = Photo(wide, tall, PixelFormat.Rgba32, 15); + var two = new PngWriteOptions { ParallelFragments = 2 }; + var file = Encode(more, wide, tall, PixelFormat.Rgba32, two, band: r => 1 + r % 40); + var buffered = PngWriter.Encode(more, wide, tall, two); + Idats(file).SelectMany(c => c).ToArray().ShouldNotBe(Idats(buffered)[0]); + DecodeOurs(file, wide, tall, PixelFormat.Rgba32).ShouldBe(more); + Math.Abs(file.Length - buffered.Length).ShouldBeLessThan(buffered.Length / 1000, "within 0.1% of the buffered size"); + } + + [Fact] + public void TheBytesDoNotDependOnHowTheRowsAreSplit() + { + const int w = 1024, h = 700; // RGBA: 2.9 MB of payload + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Bgr48 }) + { + var pixels = Photo(w, h, format, 5); + foreach (var options in new PngWriteOptions?[] { null, new() { ParallelFragments = 4 } }) + { + var whole = Encode(pixels, w, h, format, options); + Encode(pixels, w, h, format, options, band: _ => 1).ShouldBe(whole, $"{format} {options}: one row at a time"); + Encode(pixels, w, h, format, options, band: r => 1 + r % 97, seed: 2).ShouldBe(whole, $"{format} {options}: random bands"); + Encode(pixels, w, h, format, options, band: _ => 333).ShouldBe(whole, $"{format} {options}: 333 rows"); + + // Strided rows: the gaps are never read. + var rowBytes = w * format.BytesPerPixel; + var strided = new byte[(h - 1) * (rowBytes + 13) + rowBytes]; + Random.Shared.NextBytes(strided); + for (var y = 0; y < h; y++) + pixels.AsSpan(y * rowBytes, rowBytes).CopyTo(strided.AsSpan(y * (rowBytes + 13))); + var output = new ArrayBufferWriter(); + using (var session = PngImageEncoder.Create(output, options)) + { + session.AddFrame(w, h, format).WriteRows(strided, h, rowBytes + 13, Ct); + session.Commit(Ct); + } + output.WrittenSpan.ToArray().ShouldBe(whole, $"{format} {options}: strided"); + } + } + } + + [Fact] + public void BytesReachTheWriterBeforeCommit() + { + const int w = 1024, h = 512; + var pixels = Photo(w, h, PixelFormat.Rgba32, 6); + var file = StreamingAssert.EncoderEmitsBeforeCommit(o => PngImageEncoder.Create(o), pixels, w, h, PixelFormat.Rgba32); + DecodeOurs(file, w, h, PixelFormat.Rgba32).ShouldBe(pixels); + + // Two bands in flight at most: the third waits for the first, whose fragment then leaves. + const int tall = 6400; // bands of 1023 rows: three are submitted by the half + var more = Photo(w, tall, PixelFormat.Rgba32, 7); + var parallel = StreamingAssert.EncoderEmitsBeforeCommit(o => PngImageEncoder.Create(o, new PngWriteOptions { ParallelFragments = 2 }), + more, w, tall, PixelFormat.Rgba32); + DecodeOurs(parallel, w, tall, PixelFormat.Rgba32).ShouldBe(more); + } + + [Fact] + public void OptionsThatNeedTheWholeImageFallBackWithUnchangedBytes() + { + const int w = 300, h = 200; + var pixels = Photo(w, h, PixelFormat.Rgba32, 8); + var reduced = new PngWriteOptions { LosslessReduction = true }; + Encode(pixels, w, h, PixelFormat.Rgba32, reduced, band: _ => 7, expectStreaming: false).ShouldBe(PngWriter.Encode(pixels, w, h, reduced)); + var quantized = new PngWriteOptions { Quantize = new PngQuantizeOptions() }; + Encode(pixels, w, h, PixelFormat.Rgba32, quantized, band: _ => 7, expectStreaming: false).ShouldBe(PngWriter.Encode(pixels, w, h, quantized)); + var parallel = new PngWriteOptions { ParallelFragments = 4, Animation = true }; + Encode(pixels, w, h, PixelFormat.Rgba32, parallel, band: _ => 7, expectStreaming: false).ShouldBe(PngWriter.Encode(pixels, w, h, parallel)); + + using var still = PngImageEncoder.Create(new ArrayBufferWriter()); + still.MaxFrames.ShouldBe(1); + using var reducedStill = PngImageEncoder.Create(new ArrayBufferWriter(), reduced); + reducedStill.MaxFrames.ShouldBe(1); + using var animation = PngImageEncoder.Create(new ArrayBufferWriter(), new PngWriteOptions { Animation = true }); + animation.MaxFrames.ShouldBe(int.MaxValue); + } + + [Fact] + public void ASecondFrameNeedsAnimation() + { + using var session = PngImageEncoder.Create(new ArrayBufferWriter()); + session.AddFrame(2, 2, PixelFormat.Rgba32).WriteRows(new byte[16], 2, 0, Ct); + Should.Throw(() => session.AddFrame(2, 2, PixelFormat.Rgba32)); + } + + [Fact] + public void BadOptionsAreRefusedBeforeAnyByteIsWritten() + { + var output = new ArrayBufferWriter(); + using var session = PngImageEncoder.Create(output, new PngWriteOptions { TransparentColor = [1, 2, 3] }); + Should.Throw(() => session.AddFrame(4, 4, PixelFormat.Rgba32)); + using var text = PngImageEncoder.Create(output, new PngWriteOptions { Text = [new PngText(" bad", "x")] }); + Should.Throw(() => text.AddFrame(4, 4, PixelFormat.Rgb24)); + using var level = PngImageEncoder.Create(output, new PngWriteOptions { CompressionLevel = (CompressionLevel)7 }); + Should.Throw(() => level.AddFrame(4, 4, PixelFormat.Rgb24)); + output.WrittenCount.ShouldBe(0); + } + + [Fact] + public void CancellationStopsTheFrameAndDisposeWaitsForTheWorkers() + { + const int w = 1024, h = 2000; + var pixels = Photo(w, h, PixelFormat.Rgba32, 12); + foreach (var options in new PngWriteOptions?[] { null, new() { ParallelFragments = 4 } }) + { + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + var output = new ArrayBufferWriter(); + var session = PngImageEncoder.Create(output, options); + var frame = session.AddFrame(w, h, PixelFormat.Rgba32); + Should.Throw(() => frame.WriteRows(pixels, h, 0, cancelled.Token)); + + // A call whose token is cancelled when it starts consumes nothing: the frame goes on and the file is complete. + frame.WriteRows(pixels.AsSpan(0, 1500 * w * 4), 1500, 0, Ct); + Should.Throw(() => frame.WriteRows(pixels.AsSpan(1500 * w * 4), h - 1500, 0, cancelled.Token)); + frame.WriteRows(pixels.AsSpan(1500 * w * 4), h - 1500, 0, Ct); + Should.Throw(() => session.Commit(cancelled.Token)); + session.Commit(Ct); + session.Dispose(); + DecodeOurs(output.WrittenSpan.ToArray(), w, h, PixelFormat.Rgba32).ShouldBe(pixels); + + // Abandoned with bands in flight: Dispose returns once the workers are done, and nothing more is written. + var abandoned = new ArrayBufferWriter(); + var open = PngImageEncoder.Create(abandoned, options); + open.AddFrame(w, h, PixelFormat.Rgba32).WriteRows(pixels, h - 1, 0, Ct); + var written = abandoned.WrittenCount; + open.Dispose(); + abandoned.WrittenCount.ShouldBe(written); + } + } + + [Fact] + public void MemoryIsABandOfRowsNotTheImage() + { + const int w = 8192, h = 4096; // 128 MiB of RGBA + const int band = 64; + var rows = new byte[w * 4 * band]; + foreach (var options in new[] { new PngWriteOptions { CompressionLevel = CompressionLevel.Fastest }, new PngWriteOptions { CompressionLevel = CompressionLevel.Fastest, ParallelFragments = 4 } }) + { + var sink = new DiscardingWriter(); + StreamingAssert.AllocatesLessThan(4 << 20, () => + { + using var session = PngImageEncoder.Create(sink, options); + var frame = session.AddFrame(w, h, PixelFormat.Rgba32); + for (var y = 0; y < h; y += band) + { + for (var r = 0; r < band; r++) + rows.AsSpan(r * w * 4, w * 4).Fill((byte)(y + r)); + frame.WriteRows(rows, band, 0, Ct); + } + session.Commit(Ct); + }, $"a streaming encode of a 128 MiB image ({options})"); + sink.Written.ShouldBeGreaterThan(0); + } + } + + [Fact] + public void ALargePhotoStreamsToAFileAndDecodesExactly() + { + const int w = 4000, h = 3000, band = 37; + var path = Path.Combine(Path.GetTempPath(), $"png-stream-{Guid.NewGuid():N}.png"); + try + { + var pixels = Photo(w, h, PixelFormat.Bgr24, 13); + using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1)) + { + var writer = new FileWriter(file); + using var session = PngImageEncoder.Create(writer); + var frame = session.AddFrame(w, h, PixelFormat.Bgr24); + for (var y = 0; y < h; y += band) + { + var n = Math.Min(band, h - y); + frame.WriteRows(pixels.AsSpan(y * w * 3, n * w * 3), n, 0, Ct); + if (y > h / 2) + file.Length.ShouldBeGreaterThan(h, "the file grows while the rows arrive"); + } + session.Commit(Ct); + writer.LargestSpan.ShouldBeLessThanOrEqualTo(1 << 20, "the session asks for bands, not the file"); + } + var (expected, native) = Expected(pixels, w, h, PixelFormat.Bgr24); + DecodeOurs(File.ReadAllBytes(path), w, h, native).ShouldBe(expected); + } + finally + { + File.Delete(path); + } + } + + /// The data of each IDAT chunk, in order. + private static List Idats(byte[] png) + { + var chunks = new List(); + for (var at = 8; at < png.Length;) + { + var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(at)); + if (png.AsSpan(at + 4, 4).SequenceEqual("IDAT"u8)) + chunks.Add(png.AsSpan(at + 8, length).ToArray()); + at += length + 12; + } + return chunks; + } + + /// An output that counts bytes and keeps none: one reused buffer. + private sealed class DiscardingWriter : IBufferWriter + { + private byte[] _buffer = new byte[1 << 20]; + + public long Written { get; private set; } + + public void Advance(int count) => Written += 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; + } + + /// An output over a file: every goes straight to the stream. + private sealed class FileWriter(Stream stream) : IBufferWriter + { + private byte[] _buffer = new byte[4096]; + + public int LargestSpan { get; private set; } + + public void Advance(int count) => stream.Write(_buffer, 0, count); + + public Memory GetMemory(int sizeHint = 0) + { + LargestSpan = Math.Max(LargestSpan, sizeHint); + if (sizeHint > _buffer.Length) + _buffer = new byte[sizeHint]; + return _buffer; + } + + public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; + } +}