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. `PngImageDecoder.OpenRowReader(stream)` / `OpenRowReaderAsync` decode from a forward-only stream (an upload, a socket) a band of rows at a time, holding a few rows whatever the height, with exactly `TryDecodeInto`'s rows; interlaced and animated files are read whole first behind the same API (`IsStreaming` false).
- **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` 只写变化矩形,并合并不变的帧。`PngImageDecoder.OpenRowReader(stream)` / `OpenRowReaderAsync` 从只能前向读取的流(上传、套接字)按行带解码,无论图片多高只占几行的内存,行数据与 `TryDecodeInto` 逐字节相同;隔行扫描和动画文件在同一 API 后先整体读入再解码(`IsStreaming` 为 false)。
- **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
48 changes: 48 additions & 0 deletions benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ internal static class Names
public const string CurrentParallel = "CurrentParallel";
public const string CurrentReduced = "CurrentReduced";
public const string Baseline = "Baseline";
public const string Streaming = "Streaming";
public const string ImageSharp = "ImageSharp";
public const string LibPng = "LibPng";

Expand Down Expand Up @@ -73,6 +74,39 @@ public static readonly (string Name, PngAblation Flags)[] Ablations =
(Names.InflateOnly, PngAblation.InflateOnly),
];

// Every row of png through PngImageDecoder.OpenRowReader (a non-seekable read of the bytes in memory) into rows.
private static void ReadStreaming(byte[] png, byte[] rows)
{
using var reader = PngImageDecoder.OpenRowReader(new ForwardOnlyStream(png), Abstractions.PixelFormat.Rgba32);
reader.ReadRows(rows, reader.Height);
}

/// <summary>A byte array read forward only, as a network or request stream is.</summary>
private sealed class ForwardOnlyStream(byte[] data) : Stream
{
private int _position;

public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() { }
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));

public override int Read(Span<byte> buffer)
{
int n = Math.Min(buffer.Length, data.Length - _position);
data.AsSpan(_position, n).CopyTo(buffer);
_position += n;
return n;
}

public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}

/// <param name="c">The case.</param>
/// <param name="only">
/// Set up just this contestant, without the cross-checks (which would run every other one): what
Expand Down Expand Up @@ -126,6 +160,20 @@ byte[] Destination()
setup.Contestants.Add(new(Names.CurrentNative, () => Sink = PngReader.Decode(png)));
}

if (Want(Names.Streaming))
{
// The forward-only row reader over a stream of the file, every row into the same buffer layout. Its rows
// must be the span decode's before it is timed.
byte[] rows = Destination();
ReadStreaming(png, rows);
if (verify && !rows.AsSpan().SequenceEqual(current))
{
throw new InvalidOperationException($"{c.Name}: the streaming reader's rows differ from TryDecodeIntoRgba8; refusing to benchmark.");
}

setup.Contestants.Add(new(Names.Streaming, () => ReadStreaming(png, rows)));
}

if (Settings.Ablate && only is null)
{
foreach ((string name, PngAblation flags) in Ablations)
Expand Down
29 changes: 28 additions & 1 deletion benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,32 @@ public static string RenderDecode(IReadOnlyList<(DecodeSetup Setup, Dictionary<s
}
}

if (rows.Any(r => r.Ms.ContainsKey(Names.Streaming)))
{
sb.AppendLine();
sb.AppendLine("Streaming = `PngImageDecoder.OpenRowReader` over a forward-only stream of the file, every row read into the " +
"same RGBA buffer (rows identical to current, checked before timing).");
sb.AppendLine();
sb.AppendLine("| Case | current | streaming | streaming ÷ current |");
sb.AppendLine("|---|---:|---:|---:|");
foreach ((DecodeSetup s, Dictionary<string, double> ms) in rows)
{
if (ms.ContainsKey(Names.Streaming))
{
sb.AppendLine($"| `{s.Case.Name}` | {Ms(ms, Names.Current)} | {Ms(ms, Names.Streaming)} | {Ratio(ms, Names.Streaming, Names.Current)} |");
}
}

foreach (string content in SourceImage.Contents)
{
var subset = rows.Where(r => r.Setup.Case.Content == content).Select(r => r.Ms).ToList();
if (GeoMean(subset, Names.Streaming, Names.Current) is { } g)
{
sb.AppendLine($"- streaming ÷ current, {content}: {g.ToString("F3", CultureInfo.InvariantCulture)}× ({subset.Count(m => m.ContainsKey(Names.Streaming) && m.ContainsKey(Names.Current))} cases)");
}
}
}

if (rows.Any(r => r.Ms.ContainsKey(Names.InflateOnly)))
{
sb.AppendLine();
Expand All @@ -154,7 +180,7 @@ public static string RenderDecode(IReadOnlyList<(DecodeSetup Setup, Dictionary<s
}

AppendAllocations(sb, rows.Select(r => (r.Setup.Case.Name, r.Setup.Allocated)).ToList(),
[Names.Current, Names.CurrentNative, Names.Baseline, Names.ImageSharp, Names.LibPng]);
[Names.Current, Names.CurrentNative, Names.Streaming, Names.Baseline, Names.ImageSharp, Names.LibPng]);
AppendNotes(sb, notes);
return sb.ToString();
}
Expand Down Expand Up @@ -284,6 +310,7 @@ private static void AppendNotes(StringBuilder sb, List<string> notes)
Names.CurrentNative => "native",
Names.CurrentParallel => "parallel",
Names.CurrentReduced => "reduced",
Names.Streaming => "streaming",
_ => name,
};

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 @@ -33,6 +33,9 @@ public class PngDecodeBenchmarks
[Benchmark]
public void Baseline() => _run[Names.Baseline]();

[Benchmark]
public void Streaming() => _run[Names.Streaming]();

[Benchmark]
public void ImageSharp() => _run[Names.ImageSharp]();

Expand All @@ -51,7 +54,7 @@ public class PngDecodeBenchmarks
[Benchmark]
public void InflateOnly() => _run[Names.InflateOnly]();

public static readonly string[] Methods = [Names.Current, Names.CurrentNative, Names.Baseline, Names.ImageSharp, Names.LibPng];
public static readonly string[] Methods = [Names.Current, Names.CurrentNative, Names.Streaming, Names.Baseline, Names.ImageSharp, Names.LibPng];
}

/// <summary>BenchmarkDotNet over the encode cases; see <see cref="PngDecodeBenchmarks"/>.</summary>
Expand All @@ -76,6 +79,9 @@ public class PngEncodeBenchmarks
[Benchmark]
public void Baseline() => _run[Names.Baseline]();

[Benchmark]
public void Streaming() => _run[Names.Streaming]();

[Benchmark]
public void ImageSharp() => _run[Names.ImageSharp]();

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 @@ -26,6 +26,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 | — |
| `streaming` (decode) | `PngImageDecoder.OpenRowReader` over a forward-only stream of the file, every row into the same RGBA buffer; its rows must equal `current`'s before it is timed, and the report gains a streaming ÷ current table | — |
| `parallel` (encode) | — | the same with `ParallelFragments = Environment.ProcessorCount`; reported in its own table, never in the single-thread ratios |
| `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 |
Expand Down
Loading