Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Upgrading from 1.x: [docs/migrating-to-2.0.md](docs/migrating-to-2.0.md).
<summary>Feature details per package</summary>

- **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.
Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ ImageCodecs.Register(HeifImageDecoder.Registration);
<summary>各包的详细特性</summary>

- **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 里。
Expand Down
46 changes: 45 additions & 1 deletion benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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";
Expand Down Expand Up @@ -258,7 +262,7 @@ void Add(string name, Func<byte[]> 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.");
}
Expand All @@ -277,6 +281,12 @@ void Add(string name, Func<byte[]> 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<byte>();
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));
Expand Down Expand Up @@ -323,6 +333,40 @@ void Add(string name, Func<byte[]> encode, Action? timed = null)
return setup;
}

/// <summary>Rows per <c>WriteRows</c> call of the session contestants.</summary>
public const int SessionBand = 16;

private static ReadOnlyMemory<byte> EncodeSession(EncodeFormat format, byte[] samples, int width, int height, PngWriteOptions options,
ArrayBufferWriter<byte> 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),
Expand Down
36 changes: 35 additions & 1 deletion benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,32 @@ public static string RenderEncode(IReadOnlyList<(EncodeSetup Setup, Dictionary<s
}
}

if (rows.Any(r => 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<string, double> 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();
Expand All @@ -234,7 +260,7 @@ public static string RenderEncode(IReadOnlyList<(EncodeSetup Setup, Dictionary<s
}

AppendAllocations(sb, rows.Select(r => (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();
}
Expand Down Expand Up @@ -284,6 +310,8 @@ private static void AppendNotes(StringBuilder sb, List<string> notes)
Names.CurrentNative => "native",
Names.CurrentParallel => "parallel",
Names.CurrentReduced => "reduced",
Names.Streaming => "streaming",
Names.StreamingParallel => "streaming parallel",
_ => name,
};

Expand All @@ -310,6 +338,12 @@ private static string SizeRatio(EncodeSetup s, string competitor) =>
? ((double)a / b).ToString("F3", CultureInfo.InvariantCulture)
: "—";

/// <summary>Size of <paramref name="a"/> over <paramref name="b"/> to five places: streaming moves sizes by hundredths of a percent.</summary>
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<double> values)
{
values.Sort();
Expand Down
8 changes: 7 additions & 1 deletion benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]();

Expand All @@ -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];
}

/// <summary>Runs every contestant on one case before moving to the next.</summary>
Expand Down
1 change: 1 addition & 0 deletions benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Rgba32>` + `CopyPixelDataTo`, `MaxDegreeOfParallelism = 1` | `PngEncoder` with the same colour type, depth and zlib level (0 / 1 / 6 / 9), adaptive filters |
Expand Down
Loading