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
32 changes: 28 additions & 4 deletions benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/AbBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
using Sdcb.SimdCodecs.Abstractions;
using Sdcb.SimdCodecs.Abstractions.CodecSupport;

namespace Sdcb.SimdCodecs.Webp.Benchmarks;

Expand Down Expand Up @@ -66,6 +68,26 @@ public void Setup()
[Benchmark]
public void LibWebp() => Benchmarks.LibWebp.DecodeRgbaInto(_source, _rgba, _width, _height);

/// <summary>The current decoder through its forward-only row reader, 16 rows per read, from a stream.</summary>
[Benchmark]
public void Streaming() => StreamingDecode(_source, _rgba);

/// <summary>
/// Reads every row of <paramref name="source"/> through <see cref="WebpImageDecoder.CreateRowReader"/> into
/// <paramref name="rgba"/>, as a caller with a request body would: a stream, a band of 16 rows per call.
/// </summary>
internal static void StreamingDecode(byte[] source, byte[] rgba)
{
using var reader = WebpImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(source, writable: false)),
PixelFormat.Rgba32, null);
reader.Initialize();
int rowBytes = reader.Width * 4;
while (reader.RowsRead < reader.Height)
{
reader.ReadRows(rgba.AsSpan(reader.RowsRead * rowBytes), 16);
}
}

[Benchmark]
public void NoLoopFilter() => WebpDiagnostics.DecodeTo(_source, _rgba, WebpAblation.SkipLoopFilter);

Expand Down Expand Up @@ -93,7 +115,7 @@ public void Setup()
[Benchmark]
public void NoPredictorTransform() => WebpDiagnostics.DecodeTo(_source, _rgba, WebpAblation.SkipPredictorTransform);

public static readonly string[] CoreMethods = [nameof(Baseline), nameof(Current), nameof(LibWebp)];
public static readonly string[] CoreMethods = [nameof(Baseline), nameof(Current), nameof(LibWebp), nameof(Streaming)];

/// <summary>Ablations that mean something for <paramref name="input"/>.</summary>
public static string[] AblationMethods(string input)
Expand Down Expand Up @@ -138,8 +160,8 @@ internal static string RenderTable(
var sb = new StringBuilder();
sb.AppendLine($"Baseline: {baselineLabel}. Times are {source} in ms.");
sb.AppendLine();
sb.AppendLine("| Input | libwebp | baseline | current | current ÷ baseline | current ÷ libwebp |");
sb.AppendLine("|---|---:|---:|---:|---:|---:|");
sb.AppendLine("| Input | libwebp | baseline | current | current ÷ baseline | current ÷ libwebp | streaming | streaming ÷ current |");
sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|");
foreach (string input in inputs)
{
if (Get(input, nameof(Current)) is not { } current)
Expand All @@ -150,7 +172,8 @@ internal static string RenderTable(
double? lib = Get(input, nameof(LibWebp));
double? baseline = Get(input, nameof(Baseline));
sb.AppendLine($"| `{Path.GetFileName(input)}` | {(lib is { } l ? Ms(l) : "—")} | {(baseline is { } b ? Ms(b) : "—")} | {Ms(current)} | " +
$"{(baseline is { } b2 ? X(current / b2) : "—")} | {(lib is { } l2 ? X(current / l2) : "—")} |");
$"{(baseline is { } b2 ? X(current / b2) : "—")} | {(lib is { } l2 ? X(current / l2) : "—")} | " +
$"{(Get(input, nameof(Streaming)) is { } st ? Ms(st) + " | " + X(st / current) : "— | —")} |");
}

if (allocated is { Count: > 0 })
Expand Down Expand Up @@ -240,6 +263,7 @@ public static void Run(IReadOnlyList<string> inputs, bool ablate, int rounds, bo
{
(nameof(AbBenchmarks.Current), () => WebpDecoder.DecodeTo(source, rgba)),
(nameof(AbBenchmarks.LibWebp), () => LibWebp.DecodeRgbaInto(source, rgba, info.Width, info.Height)),
(nameof(AbBenchmarks.Streaming), () => AbBenchmarks.StreamingDecode(source, rgba)),
};
if (hasBaseline)
{
Expand Down
7 changes: 7 additions & 0 deletions benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,13 @@ static void CheckCorrectness(IReadOnlyList<string> inputs, bool requireBaseline)
throw new InvalidOperationException($"{input}: current decoder output differs from libwebp; refusing to benchmark.");
}

byte[] streamed = new byte[current.Length];
AbBenchmarks.StreamingDecode(source, streamed);
if (!streamed.AsSpan().SequenceEqual(current))
{
throw new InvalidOperationException($"{input}: the streaming reader's rows differ from DecodeTo; refusing to benchmark.");
}

string vsBaseline = "no baseline";
if (BaselineDecoder.Description is not null)
{
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ dotnet run -c Release --project benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks -- ab
dotnet run -c Release --project benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks -- quick [--ablate] [--inputs RE|--files PATTERN] [--rounds N] [--mt] [--scaled]
```

`baseline` builds a commit's decoder into `.cache/baseline/` (through a temporary git worktree) and loads it into its own `AssemblyLoadContext`, so `ab` times baseline, current and libwebp in one BenchmarkDotNet run, interleaved per input — never against a number from an earlier session. Both `ab` and `quick` first check that the current decoder's output is byte-identical to libwebp and refuse to time it otherwise. `--ablate` adds runs with one stage switched off (internal `WebpAblation` flags via `WebpDiagnostics`): a stage's cost is the time that disappears (the set of ablations is chosen from the file's content: VP8 stages, ALPH, or VP8L transforms and the predictor transform alone). `quick` is an in-process interleaved loop that answers in seconds; use it while iterating and `ab` for the numbers that go into a commit. It warms every contestant for at least 300 ms first, so small files are not timed as tier-0 code. `--files PATTERN` times files of the verification corpus (below) instead of the three inputs — the inputs are flat `testsrc2` frames, and the corpus' noisy content is where entropy decoding dominates. `--mt` adds the opt-in multithreaded decode (`WebpDecodeOptions.Multithreaded`) as a separate table; it is never part of the single-thread comparison. `--scaled` adds region and scale decodes of the lossy stills through `WebpImageDecoder.TryDecodeInto` (1/2, 1/4, 1/8, and a 640×270 region at the top, middle and bottom at full scale) as a separate table: the current build's native path against the baseline's, each checked byte-identical to the baseline's output before timing (it needs a baseline).
`baseline` builds a commit's decoder into `.cache/baseline/` (through a temporary git worktree) and loads it into its own `AssemblyLoadContext`, so `ab` times baseline, current and libwebp in one BenchmarkDotNet run, interleaved per input — never against a number from an earlier session. Both `ab` and `quick` first check that the current decoder's output is byte-identical to libwebp and refuse to time it otherwise. Both also time `Streaming`: the current decoder through `WebpImageDecoder.CreateRowReader` from a `MemoryStream`, 16 rows per read (checked identical to `DecodeTo` first), reported as `streaming ÷ current`; lossless input takes the reader's buffered fallback there. `--ablate` adds runs with one stage switched off (internal `WebpAblation` flags via `WebpDiagnostics`): a stage's cost is the time that disappears (the set of ablations is chosen from the file's content: VP8 stages, ALPH, or VP8L transforms and the predictor transform alone). `quick` is an in-process interleaved loop that answers in seconds; use it while iterating and `ab` for the numbers that go into a commit. It warms every contestant for at least 300 ms first, so small files are not timed as tier-0 code. `--files PATTERN` times files of the verification corpus (below) instead of the three inputs — the inputs are flat `testsrc2` frames, and the corpus' noisy content is where entropy decoding dominates. `--mt` adds the opt-in multithreaded decode (`WebpDecodeOptions.Multithreaded`) as a separate table; it is never part of the single-thread comparison. `--scaled` adds region and scale decodes of the lossy stills through `WebpImageDecoder.TryDecodeInto` (1/2, 1/4, 1/8, and a 640×270 region at the top, middle and bottom at full scale) as a separate table: the current build's native path against the baseline's, each checked byte-identical to the baseline's output before timing (it needs a baseline).

### Memory

Expand Down
1 change: 1 addition & 0 deletions src/Sdcb.SimdCodecs.Webp/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static Sdcb.SimdCodecs.Webp.WebpImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader!
16 changes: 16 additions & 0 deletions src/Sdcb.SimdCodecs.Webp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,22 @@ Decoding is single-threaded by default. Opt in to decoding the transparency plan
WebpDecoder.DecodeTo(data, rgba, 0, new WebpDecodeOptions { Multithreaded = true });
```

Read a lossy still from a forward-only stream (a request body, a socket), a band of rows at a time, synchronously or asynchronously. Rows are decoded as the VP8 chunk's bytes arrive: with one token partition (what encoders write by default) from a window of about two macroblock rows of compressed input, so memory is O(width) whatever the height; with several partitions the VP8 chunk is buffered first (O(compressed chunk) + O(width)). An ALPH transparency plane is decoded whole with the header (width × height bytes). Lossless and animated files, and region or scale options, read the whole stream and decode it as `TryDecodeInto` does (`IsStreaming` is false). The rows equal `TryDecodeInto`'s byte for byte; `Info` lacks what is stored after the image (an EXIF orientation, usually), and a file that stores its ALPH chunk, or an animated VP8X chunk, after the image data is refused with `InvalidDataException`:

```csharp
using Sdcb.SimdCodecs.Abstractions;
using Sdcb.SimdCodecs.Abstractions.CodecSupport;

await using var reader = WebpImageDecoder.CreateRowReader(new StreamInput(requestBody), PixelFormat.Rgba32, null);
await reader.InitializeAsync();
byte[] band = new byte[reader.Width * 4 * 16];
int rows;
while ((rows = await reader.ReadRowsAsync(band, 16)) > 0)
{
// rows × (Width × 4) bytes of band are the next rows.
}
```

Decode every frame into a full-canvas RGBA buffer:

```csharp
Expand Down
33 changes: 33 additions & 0 deletions src/Sdcb.SimdCodecs.Webp/Vp8BoolDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,44 @@ internal ref struct Vp8BoolDecoder
private int _bits;
private uint _rangeMinus1;

// Set once a refill has run out of data and fed zero bits instead.
private bool _padded;

public Vp8BoolDecoder(ReadOnlySpan<byte> data)
{
_next = ref MemoryMarshal.GetReference(data);
_remaining = data.Length;
_value = 0;
_bits = -8;
_rangeMinus1 = 254;
_padded = false;
}

/// <summary>
/// Resumes a decoder whose arithmetic state (<see cref="Load"/>) was saved after it had read every byte before
/// <paramref name="data"/>: <paramref name="data"/> starts at the first byte it had not read. The window is only
/// ever refilled with whole bytes, so the decode goes on exactly as if the input had been one span.
/// </summary>
public Vp8BoolDecoder(ReadOnlySpan<byte> data, ulong value, int bits, uint rangeMinus1)
{
_next = ref MemoryMarshal.GetReference(data);
_remaining = data.Length;
_value = value;
_bits = bits;
_rangeMinus1 = rangeMinus1;
_padded = false;
}

/// <summary>Bytes of the data not read into the window yet.</summary>
public readonly int Remaining => _remaining;

/// <summary>
/// True once the decoder has run out of data and fed zero bits: at the true end of a partition that is how the
/// stream continues (RFC 6386 §7.3), but over a window that ends before the partition does it means the decode
/// got ahead of the input, and what it decoded since may be wrong.
/// </summary>
public readonly bool Padded => _padded;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadBit(int probability)
{
Expand Down Expand Up @@ -222,6 +251,10 @@ private void RefillTail()
_next = ref Unsafe.Add(ref _next, 1);
_remaining--;
}
else
{
_padded = true;
}

_value = (_value << 8) | next;
_bits += 8;
Expand Down
Loading