diff --git a/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/AbBenchmarks.cs b/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/AbBenchmarks.cs
index 55a4a61..495d3de 100644
--- a/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/AbBenchmarks.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/AbBenchmarks.cs
@@ -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;
@@ -66,6 +68,26 @@ public void Setup()
[Benchmark]
public void LibWebp() => Benchmarks.LibWebp.DecodeRgbaInto(_source, _rgba, _width, _height);
+ /// The current decoder through its forward-only row reader, 16 rows per read, from a stream.
+ [Benchmark]
+ public void Streaming() => StreamingDecode(_source, _rgba);
+
+ ///
+ /// Reads every row of through into
+ /// , as a caller with a request body would: a stream, a band of 16 rows per call.
+ ///
+ 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);
@@ -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)];
/// Ablations that mean something for .
public static string[] AblationMethods(string input)
@@ -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)
@@ -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 })
@@ -240,6 +263,7 @@ public static void Run(IReadOnlyList 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)
{
diff --git a/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/Program.cs b/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/Program.cs
index ae0e926..24d2dbb 100644
--- a/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/Program.cs
+++ b/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/Program.cs
@@ -139,6 +139,13 @@ static void CheckCorrectness(IReadOnlyList 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)
{
diff --git a/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/README.md b/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/README.md
index eb0e835..9e1ab03 100644
--- a/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/README.md
+++ b/benchmarks/Sdcb.SimdCodecs.Webp.Benchmarks/README.md
@@ -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
diff --git a/src/Sdcb.SimdCodecs.Webp/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Webp/PublicAPI.Unshipped.txt
index 7dc5c58..b7d8fa7 100644
--- a/src/Sdcb.SimdCodecs.Webp/PublicAPI.Unshipped.txt
+++ b/src/Sdcb.SimdCodecs.Webp/PublicAPI.Unshipped.txt
@@ -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!
diff --git a/src/Sdcb.SimdCodecs.Webp/README.md b/src/Sdcb.SimdCodecs.Webp/README.md
index cc2b015..57bfe4e 100644
--- a/src/Sdcb.SimdCodecs.Webp/README.md
+++ b/src/Sdcb.SimdCodecs.Webp/README.md
@@ -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
diff --git a/src/Sdcb.SimdCodecs.Webp/Vp8BoolDecoder.cs b/src/Sdcb.SimdCodecs.Webp/Vp8BoolDecoder.cs
index 846ae54..6466e4a 100644
--- a/src/Sdcb.SimdCodecs.Webp/Vp8BoolDecoder.cs
+++ b/src/Sdcb.SimdCodecs.Webp/Vp8BoolDecoder.cs
@@ -24,6 +24,9 @@ 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 data)
{
_next = ref MemoryMarshal.GetReference(data);
@@ -31,8 +34,34 @@ public Vp8BoolDecoder(ReadOnlySpan data)
_value = 0;
_bits = -8;
_rangeMinus1 = 254;
+ _padded = false;
}
+ ///
+ /// Resumes a decoder whose arithmetic state () was saved after it had read every byte before
+ /// : 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.
+ ///
+ public Vp8BoolDecoder(ReadOnlySpan data, ulong value, int bits, uint rangeMinus1)
+ {
+ _next = ref MemoryMarshal.GetReference(data);
+ _remaining = data.Length;
+ _value = value;
+ _bits = bits;
+ _rangeMinus1 = rangeMinus1;
+ _padded = false;
+ }
+
+ /// Bytes of the data not read into the window yet.
+ public readonly int Remaining => _remaining;
+
+ ///
+ /// 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.
+ ///
+ public readonly bool Padded => _padded;
+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadBit(int probability)
{
@@ -222,6 +251,10 @@ private void RefillTail()
_next = ref Unsafe.Add(ref _next, 1);
_remaining--;
}
+ else
+ {
+ _padded = true;
+ }
_value = (_value << 8) | next;
_bits += 8;
diff --git a/src/Sdcb.SimdCodecs.Webp/Vp8Decoder.cs b/src/Sdcb.SimdCodecs.Webp/Vp8Decoder.cs
index 6860d99..800d138 100644
--- a/src/Sdcb.SimdCodecs.Webp/Vp8Decoder.cs
+++ b/src/Sdcb.SimdCodecs.Webp/Vp8Decoder.cs
@@ -124,11 +124,40 @@ internal static void DecodeFrame(
int rowLimit = int.MaxValue)
where TSink : IVp8RowSink, allows ref struct
{
- bool applyLoopFilter = (ablation & WebpAblation.SkipLoopFilter) == 0;
- bool skipResidual = (ablation & WebpAblation.SkipResidual) != 0;
- bool skipPrediction = (ablation & WebpAblation.SkipPrediction) != 0;
- bool skipCopy = (ablation & WebpAblation.SkipMacroblockCopy) != 0;
- if (frame.Length < 10)
+ int partitionLength = ReadFrameTag(frame, frame.Length, width, height);
+ var header = new Vp8BoolDecoder(frame.Slice(10, partitionLength));
+ FrameState state = FrameState.Create(ref header, width, height, ablation);
+ try
+ {
+ PartitionSlices partitions = ReadPartitions(frame[(10 + partitionLength)..], state.PartitionCount);
+ var tokens = new Vp8TokenPartitions(
+ partitions.P0, partitions.P1, partitions.P2, partitions.P3,
+ partitions.P4, partitions.P5, partitions.P6, partitions.P7);
+ int partitionMask = state.PartitionCount - 1;
+ while (state.MacroblockY < state.MacroblockHeight)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ state.ReconstructRow(ref header, ref tokens.PartitionRef(state.MacroblockY & partitionMask));
+ if (state.FinishRow(ref sink, rowLimit))
+ {
+ break;
+ }
+ }
+ }
+ finally
+ {
+ state.Dispose();
+ }
+ }
+
+ ///
+ /// Checks the 10-byte key-frame header at the start of (a VP8 chunk of
+ /// bytes, of which only the header need be present) and returns the
+ /// first partition's length.
+ ///
+ internal static int ReadFrameTag(ReadOnlySpan frame, int frameLength, int width, int height)
+ {
+ if (frameLength < 10 || frame.Length < 10)
{
throw new InvalidDataException("The VP8 key-frame header is truncated.");
}
@@ -140,7 +169,7 @@ internal static void DecodeFrame(
}
int partitionLength = (int)(frameTag >> 5);
- if (partitionLength > frame.Length - 10 ||
+ if (partitionLength > frameLength - 10 ||
frame[3] != 0x9d || frame[4] != 0x01 || frame[5] != 0x2a)
{
throw new InvalidDataException("The VP8 key-frame header or first partition is invalid.");
@@ -153,286 +182,418 @@ internal static void DecodeFrame(
throw new InvalidDataException("The WebP and VP8 dimensions do not match.");
}
- ReadOnlySpan headerPartition = frame.Slice(10, partitionLength);
- var header = new Vp8BoolDecoder(headerPartition);
- if (header.ReadBit(128) != 0)
- {
- throw new NotSupportedException("Reserved VP8 key-frame color-space flags are unsupported.");
- }
-
- _ = header.ReadBit(128);
+ return partitionLength;
+ }
- SegmentFeatures segments = ReadSegments(ref header);
- FilterSettings filter;
- try
- {
- filter = ReadFilter(ref header);
- }
- catch
- {
- ReturnSegmentBuffers(segments);
- throw;
- }
+ ///
+ /// A key frame's decoding state between macroblock rows: the frame header read from the first
+ /// partition, the row caches and the above contexts. keeps one
+ /// on its stack; a streaming reader keeps one between reads. A row is entropy-decoded and
+ /// reconstructed () before anything outside that row is touched
+ /// (), so a row whose input ran out can be retried: restore the
+ /// above contexts ( / ) and the two bool
+ /// decoders, and decode it again.
+ ///
+ internal struct FrameState
+ {
+ private SegmentFeatures _segments;
+ private FilterSettings _filter;
+ private SegmentParameterSet _segmentParameters;
+ private byte[] _probabilities;
+ private int _skipProbability; // -1 when macroblocks carry no skip flag
+ private byte[] _yCache;
+ private byte[] _uCache;
+ private byte[] _vCache;
+ private byte[] _topRows;
+ private byte[] _aboveB;
+ private uint[] _aboveNz;
+ private byte[] _rowFilter;
+ private byte[]? _savedAboveB;
+ private uint[]? _savedAboveNz;
+ private int _width;
+ private int _height;
+ private int _yStride;
+ private int _uvStride;
+ private int _paddedWidth;
+ private WebpAblation _ablation;
+
+ /// The number of token partitions (1, 2, 4 or 8).
+ public int PartitionCount { readonly get; private set; }
+
+ public int MacroblockWidth { readonly get; private set; }
+
+ public int MacroblockHeight { readonly get; private set; }
+
+ /// The macroblock row decodes next.
+ public int MacroblockY { readonly get; private set; }
+
+ /// Rows handed to the sink so far.
+ public int Emitted { readonly get; private set; }
+
+ ///
+ /// Reads the frame header from the first partition (, left positioned
+ /// at the first macroblock's modes) and rents the row caches.
+ ///
+ public static FrameState Create(ref Vp8BoolDecoder header, int width, int height, WebpAblation ablation)
+ {
+ if (header.ReadBit(128) != 0)
+ {
+ throw new NotSupportedException("Reserved VP8 key-frame color-space flags are unsupported.");
+ }
- byte[] coefficientProbabilities = Array.Empty();
- bool coefficientProbabilitiesRented = false;
- int partitionCount;
- Quantizers quantizers;
- bool skipFlagPresent;
- byte skipProbability;
- PartitionSlices partitions;
- try
- {
- partitionCount = 1 << header.ReadLiteral(2);
- quantizers = ReadQuantizers(ref header);
_ = header.ReadBit(128);
- coefficientProbabilities = WebpBufferPool.Rent(4 * 8 * 3 * 11);
- coefficientProbabilitiesRented = true;
- Vp8Tables.CopyDefaultCoefficientProbabilities(coefficientProbabilities);
- ReadCoefficientProbabilityUpdates(ref header, coefficientProbabilities);
- skipFlagPresent = header.ReadBit(128) != 0;
- skipProbability = skipFlagPresent ? (byte)header.ReadLiteral(8) : (byte)0;
- ReadOnlySpan tokenFrame = frame[(10 + partitionLength)..];
- partitions = ReadPartitions(tokenFrame, partitionCount);
- }
- catch
- {
- if (coefficientProbabilitiesRented)
+ SegmentFeatures segments = ReadSegments(ref header);
+ FilterSettings filter;
+ try
{
- WebpBufferPool.Return(coefficientProbabilities);
+ filter = ReadFilter(ref header);
+ }
+ catch
+ {
+ ReturnSegmentBuffers(segments);
+ throw;
}
- ReturnSegmentBuffers(segments);
- ReturnFilterBuffers(filter);
- throw;
- }
-
- var tokens = new Vp8TokenPartitions(
- partitions.P0, partitions.P1, partitions.P2, partitions.P3,
- partitions.P4, partitions.P5, partitions.P6, partitions.P7);
-
- int mbWidth = (width + 15) >> 4;
- int mbHeight = (height + 15) >> 4;
- int paddedWidth = mbWidth * 16;
- // Cache rows carry CacheLeft bytes before column 0: column -1 is the 129 left frame edge
- // intra prediction reads; the rest keeps rows aligned.
- int yStride = paddedWidth + 2 * CacheLeft;
- int uvStride = paddedWidth / 2 + 2 * CacheLeft;
- byte[] yCache = WebpBufferPool.Rent(checked(yStride * (LumaCacheExtra + 16)));
- byte[] uCache = WebpBufferPool.Rent(checked(uvStride * (ChromaCacheExtra + 8)));
- byte[] vCache = WebpBufferPool.Rent(checked(uvStride * (ChromaCacheExtra + 8)));
- // Unfiltered bottom rows of the previous macroblock row: intra prediction reads these, while
- // the cache above the current row holds them loop-filtered.
- byte[] topRows = WebpBufferPool.Rent(checked(paddedWidth * 2));
- byte[] aboveB = WebpBufferPool.Rent(mbWidth * 4);
- uint[] aboveNz = WebpBufferPool.Rent(mbWidth);
- byte[] rowFilter = WebpBufferPool.Rent(mbWidth * 2);
- // The row above the macroblock being predicted, with its top-left pixel at index -1:
- // luma 16 + 4 above-right (at AboveY), U and V 8 (at AboveU / AboveV).
- Span aboveRows = stackalloc byte[AboveLength];
- Span blockModes = stackalloc byte[16];
- Span leftB = stackalloc byte[4];
- uint leftNz = 0;
- Span residual = stackalloc short[16];
- // 25 blocks of 16 coefficients: 16 luma, 4 U, 4 V, Y2. Kept zero between blocks: each block
- // is cleared right after it has been consumed.
- Span mbCoefficients = stackalloc short[25 * 16];
- mbCoefficients.Clear();
- SegmentParameterSet segmentParameters = default;
- ComputeSegmentParameters(segments, quantizers, filter, segmentParameters);
- ref byte probabilityBase = ref MemoryMarshal.GetArrayDataReference(coefficientProbabilities);
+ byte[] coefficientProbabilities = Array.Empty();
+ bool coefficientProbabilitiesRented = false;
+ int partitionCount;
+ Quantizers quantizers;
+ int skipProbability;
+ try
+ {
+ partitionCount = 1 << header.ReadLiteral(2);
+ quantizers = ReadQuantizers(ref header);
+ _ = header.ReadBit(128);
+ coefficientProbabilities = WebpBufferPool.Rent(4 * 8 * 3 * 11);
+ coefficientProbabilitiesRented = true;
+ Vp8Tables.CopyDefaultCoefficientProbabilities(coefficientProbabilities);
+ ReadCoefficientProbabilityUpdates(ref header, coefficientProbabilities);
+ bool skipFlagPresent = header.ReadBit(128) != 0;
+ skipProbability = skipFlagPresent ? (byte)header.ReadLiteral(8) : -1;
+ }
+ catch
+ {
+ if (coefficientProbabilitiesRented)
+ {
+ WebpBufferPool.Return(coefficientProbabilities);
+ }
- try
- {
- Array.Clear(aboveB);
- Array.Clear(aboveNz);
+ ReturnSegmentBuffers(segments);
+ ReturnFilterBuffers(filter);
+ throw;
+ }
+
+ int mbWidth = (width + 15) >> 4;
+ int paddedWidth = mbWidth * 16;
+ var state = new FrameState
+ {
+ _segments = segments,
+ _filter = filter,
+ _probabilities = coefficientProbabilities,
+ _skipProbability = skipProbability,
+ _width = width,
+ _height = height,
+ _paddedWidth = paddedWidth,
+ // Cache rows carry CacheLeft bytes before column 0: column -1 is the 129 left frame edge
+ // intra prediction reads; the rest keeps rows aligned.
+ _yStride = paddedWidth + 2 * CacheLeft,
+ _uvStride = paddedWidth / 2 + 2 * CacheLeft,
+ _ablation = ablation,
+ PartitionCount = partitionCount,
+ MacroblockWidth = mbWidth,
+ MacroblockHeight = (height + 15) >> 4,
+ };
+ state._yCache = WebpBufferPool.Rent(checked(state._yStride * (LumaCacheExtra + 16)));
+ state._uCache = WebpBufferPool.Rent(checked(state._uvStride * (ChromaCacheExtra + 8)));
+ state._vCache = WebpBufferPool.Rent(checked(state._uvStride * (ChromaCacheExtra + 8)));
+ // Unfiltered bottom rows of the previous macroblock row: intra prediction reads these, while
+ // the cache above the current row holds them loop-filtered.
+ state._topRows = WebpBufferPool.Rent(checked(paddedWidth * 2));
+ state._aboveB = WebpBufferPool.Rent(mbWidth * 4);
+ state._aboveNz = WebpBufferPool.Rent(mbWidth);
+ state._rowFilter = WebpBufferPool.Rent(mbWidth * 2);
+ Array.Clear(state._aboveB);
+ Array.Clear(state._aboveNz);
+ ComputeSegmentParameters(segments, quantizers, filter, state._segmentParameters);
+ return state;
+ }
+
+ /// Copies the above contexts that updates.
+ public void SaveContexts()
+ {
+ int mbWidth = MacroblockWidth;
+ _savedAboveB ??= WebpBufferPool.Rent(mbWidth * 4);
+ _savedAboveNz ??= WebpBufferPool.Rent(mbWidth);
+ _aboveB.AsSpan(0, mbWidth * 4).CopyTo(_savedAboveB);
+ _aboveNz.AsSpan(0, mbWidth).CopyTo(_savedAboveNz);
+ }
+
+ /// Puts back the contexts copied, undoing a .
+ public readonly void RestoreContexts()
+ {
+ int mbWidth = MacroblockWidth;
+ _savedAboveB.AsSpan(0, mbWidth * 4).CopyTo(_aboveB);
+ _savedAboveNz.AsSpan(0, mbWidth).CopyTo(_aboveNz);
+ }
+
+ ///
+ /// Entropy-decodes macroblock row (modes from ,
+ /// coefficients from ) and reconstructs it, unfiltered, into the
+ /// row cache. Nothing but the row's cache rows and the above contexts changes, so the row can be
+ /// decoded again after (a streaming reader does when
+ /// read past its window: ). That
+ /// check is the caller's, once per row: a test in the macroblock loop measured 8% slower.
+ ///
+ public void ReconstructRow(ref Vp8BoolDecoder header, ref Vp8BoolDecoder tokenDecoder)
+ {
+ bool skipResidual = (_ablation & WebpAblation.SkipResidual) != 0;
+ bool skipPrediction = (_ablation & WebpAblation.SkipPrediction) != 0;
+ bool skipCopy = (_ablation & WebpAblation.SkipMacroblockCopy) != 0;
+ int width = _width;
+ int mbWidth = MacroblockWidth;
+ int mbY = MacroblockY;
+ int yStride = _yStride;
+ int uvStride = _uvStride;
+ int paddedWidth = _paddedWidth;
+ byte[] aboveB = _aboveB;
+ uint[] aboveNz = _aboveNz;
+ byte[] rowFilter = _rowFilter;
+ byte[]? segmentProbabilities = _segments.Enabled && _segments.UpdateMap ? _segments.MapProbabilities : null;
+ int skipProbability = _skipProbability;
+
+ // The row above the macroblock being predicted, with its top-left pixel at index -1:
+ // luma 16 + 4 above-right (at AboveY), U and V 8 (at AboveU / AboveV).
+ Span aboveRows = stackalloc byte[AboveLength];
+ Span blockModes = stackalloc byte[16];
+ Span leftB = stackalloc byte[4];
+ uint leftNz = 0;
+ Span residual = stackalloc short[16];
+ // 25 blocks of 16 coefficients: 16 luma, 4 U, 4 V, Y2. Kept zero between blocks: each block
+ // is cleared right after it has been consumed.
+ Span mbCoefficients = stackalloc short[25 * 16];
+ mbCoefficients.Clear();
+ leftB.Clear();
+ ref byte probabilityBase = ref MemoryMarshal.GetArrayDataReference(_probabilities);
ref byte aboveY = ref Unsafe.Add(ref MemoryMarshal.GetReference(aboveRows), AboveY);
ref byte aboveU = ref Unsafe.Add(ref MemoryMarshal.GetReference(aboveRows), AboveU);
ref byte aboveV = ref Unsafe.Add(ref MemoryMarshal.GetReference(aboveRows), AboveV);
- ref byte topY = ref MemoryMarshal.GetArrayDataReference(topRows);
+ ref byte topY = ref MemoryMarshal.GetArrayDataReference(_topRows);
ref byte topU = ref Unsafe.Add(ref topY, paddedWidth);
ref byte topV = ref Unsafe.Add(ref topU, paddedWidth / 2);
- ref byte yRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(yCache), LumaCacheExtra * yStride + CacheLeft);
- ref byte uRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(uCache), ChromaCacheExtra * uvStride + CacheLeft);
- ref byte vRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(vCache), ChromaCacheExtra * uvStride + CacheLeft);
- int emitted = 0;
- for (int mbY = 0; mbY < mbHeight; mbY++)
+ ref byte yRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_yCache), LumaCacheExtra * yStride + CacheLeft);
+ ref byte uRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_uCache), ChromaCacheExtra * uvStride + CacheLeft);
+ ref byte vRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_vCache), ChromaCacheExtra * uvStride + CacheLeft);
+ for (int row = 0; row < 16; row++)
{
- cancellationToken.ThrowIfCancellationRequested();
- for (int row = 0; row < 16; row++)
+ Unsafe.Add(ref yRow0, row * yStride - 1) = 129;
+ }
+
+ for (int row = 0; row < 8; row++)
+ {
+ Unsafe.Add(ref uRow0, row * uvStride - 1) = 129;
+ Unsafe.Add(ref vRow0, row * uvStride - 1) = 129;
+ }
+
+ for (int mbX = 0; mbX < mbWidth; mbX++)
+ {
+ int modes = ReadMacroblockModes(ref header, segmentProbabilities, skipProbability,
+ aboveB.AsSpan(mbX * 4, 4), leftB, blockModes);
+ int segment = modes & 3;
+ bool skip = (modes & 4) != 0;
+ byte yMode = (byte)((modes >> 3) & 7);
+ byte uvMode = (byte)(modes >> 6);
+ ref SegmentParameters sp = ref _segmentParameters[segment];
+ ref short coefficientBase = ref MemoryMarshal.GetReference(mbCoefficients);
+ bool i16 = yMode != 4;
+ ulong masks = 0;
+ if (skip)
{
- Unsafe.Add(ref yRow0, row * yStride - 1) = 129;
+ // A skipped macroblock has no coefficients; only a Y2 context survives, and
+ // only when the macroblock has no Y2 block itself (RFC 6386 §13.3).
+ uint keep = i16 ? 0u : NzY2;
+ aboveNz[mbX] &= keep;
+ leftNz &= keep;
+ }
+ else
+ {
+ masks = ParseResiduals(ref tokenDecoder, ref probabilityBase, ref coefficientBase, ref sp, i16,
+ ref aboveNz[mbX], ref leftNz);
}
- for (int row = 0; row < 8; row++)
+ uint nonzeroMask = (uint)masks;
+ uint acMask = (uint)(masks >> 32);
+ rowFilter[mbX * 2] = i16 ? sp.FilterLevelI16 : sp.FilterLevelI4;
+ // Inner edges are filtered unless the macroblock is i16 with no coefficients.
+ rowFilter[mbX * 2 + 1] = (byte)(nonzeroMask == 0 && i16 ? 0 : 1);
+
+ if (!skipCopy)
{
- Unsafe.Add(ref uRow0, row * uvStride - 1) = 129;
- Unsafe.Add(ref vRow0, row * uvStride - 1) = 129;
+ PrepareAbove(ref aboveY, ref aboveU, ref aboveV, ref topY, ref topU, ref topV, mbX, mbY, width);
}
- leftB.Clear();
- leftNz = 0;
- int tokenPartition = mbY & (partitionCount - 1);
- ref Vp8BoolDecoder tokenDecoder = ref tokens.PartitionRef(tokenPartition);
- for (int mbX = 0; mbX < mbWidth; mbX++)
+ ref byte dy = ref Unsafe.Add(ref yRow0, mbX * 16);
+ ref byte du = ref Unsafe.Add(ref uRow0, mbX * 8);
+ ref byte dv = ref Unsafe.Add(ref vRow0, mbX * 8);
+ if (!skipPrediction)
{
- int modes = ReadMacroblockModes(ref header, segments.Enabled && segments.UpdateMap ? segments.MapProbabilities : null,
- skipFlagPresent ? skipProbability : -1, aboveB.AsSpan(mbX * 4, 4), leftB, blockModes);
- int segment = modes & 3;
- bool skip = (modes & 4) != 0;
- byte yMode = (byte)((modes >> 3) & 7);
- byte uvMode = (byte)(modes >> 6);
- ref SegmentParameters sp = ref segmentParameters[segment];
- ref short coefficientBase = ref MemoryMarshal.GetReference(mbCoefficients);
- bool i16 = yMode != 4;
- ulong masks = 0;
- if (skip)
+ if (i16)
{
- // A skipped macroblock has no coefficients; only a Y2 context survives, and
- // only when the macroblock has no Y2 block itself (RFC 6386 §13.3).
- uint keep = i16 ? 0u : NzY2;
- aboveNz[mbX] &= keep;
- leftNz &= keep;
- }
- else
- {
- masks = ParseResiduals(ref tokenDecoder, ref probabilityBase, ref coefficientBase, ref sp, i16,
- ref aboveNz[mbX], ref leftNz);
+ PredictLarge(ref dy, yStride, 16, yMode, mbY > 0, mbX > 0, ref aboveY);
}
- uint nonzeroMask = (uint)masks;
- uint acMask = (uint)(masks >> 32);
- rowFilter[mbX * 2] = i16 ? sp.FilterLevelI16 : sp.FilterLevelI4;
- // Inner edges are filtered unless the macroblock is i16 with no coefficients.
- rowFilter[mbX * 2 + 1] = (byte)(nonzeroMask == 0 && i16 ? 0 : 1);
+ PredictLarge(ref du, uvStride, 8, uvMode, mbY > 0, mbX > 0, ref aboveU);
+ PredictLarge(ref dv, uvStride, 8, uvMode, mbY > 0, mbX > 0, ref aboveV);
+ }
+
+ if (i16 && (nonzeroMask & NzY2) != 0)
+ {
+ ref short y2 = ref Unsafe.Add(ref coefficientBase, 24 * 16);
+ InverseWalshToBlocks(ref y2, ref coefficientBase, (acMask & NzY2) != 0);
+ Unsafe.InitBlockUnaligned(ref Unsafe.As(ref y2), 0, 32);
+ }
- if (!skipCopy)
+ for (int block = 0; block < 16; block++)
+ {
+ int blockX = block & 3;
+ int blockY = block >> 2;
+ ref byte destination = ref Unsafe.Add(ref dy, blockY * 4 * yStride + blockX * 4);
+ if (!i16 && !skipPrediction)
{
- PrepareAbove(ref aboveY, ref aboveU, ref aboveV, ref topY, ref topU, ref topV, mbX, mbY, width);
+ PredictSubblock(ref destination, yStride, blockModes[block],
+ ref SubblockAbove(ref destination, yStride, blockX, blockY, ref aboveY, aboveRows));
}
- ref byte dy = ref Unsafe.Add(ref yRow0, mbX * 16);
- ref byte du = ref Unsafe.Add(ref uRow0, mbX * 8);
- ref byte dv = ref Unsafe.Add(ref vRow0, mbX * 8);
- if (!skipPrediction)
+ // An i16 block can be all zero except for the DC its Y2 block supplied.
+ ref short coefficients = ref Unsafe.Add(ref coefficientBase, block * 16);
+ if (((nonzeroMask >> block) & 1) != 0 || coefficients != 0)
{
- if (i16)
+ if (!skipResidual)
{
- PredictLarge(ref dy, yStride, 16, yMode, mbY > 0, mbX > 0, ref aboveY);
+ InverseDctAdd(ref coefficients, ref destination, yStride, residual, ((acMask >> block) & 1) != 0);
}
- PredictLarge(ref du, uvStride, 8, uvMode, mbY > 0, mbX > 0, ref aboveU);
- PredictLarge(ref dv, uvStride, 8, uvMode, mbY > 0, mbX > 0, ref aboveV);
- }
-
- if (i16 && (nonzeroMask & NzY2) != 0)
- {
- ref short y2 = ref Unsafe.Add(ref coefficientBase, 24 * 16);
- InverseWalshToBlocks(ref y2, ref coefficientBase, (acMask & NzY2) != 0);
- Unsafe.InitBlockUnaligned(ref Unsafe.As(ref y2), 0, 32);
+ Unsafe.InitBlockUnaligned(ref Unsafe.As(ref coefficients), 0, 32);
}
+ }
- for (int block = 0; block < 16; block++)
+ if ((nonzeroMask & 0xff0000) != 0)
+ {
+ for (int block = 16; block < 24; block++)
{
- int blockX = block & 3;
- int blockY = block >> 2;
- ref byte destination = ref Unsafe.Add(ref dy, blockY * 4 * yStride + blockX * 4);
- if (!i16 && !skipPrediction)
+ if (((nonzeroMask >> block) & 1) == 0)
{
- PredictSubblock(ref destination, yStride, blockModes[block],
- ref SubblockAbove(ref destination, yStride, blockX, blockY, ref aboveY, aboveRows));
+ continue;
}
- // An i16 block can be all zero except for the DC its Y2 block supplied.
ref short coefficients = ref Unsafe.Add(ref coefficientBase, block * 16);
- if (((nonzeroMask >> block) & 1) != 0 || coefficients != 0)
+ if (!skipResidual)
{
- if (!skipResidual)
- {
- InverseDctAdd(ref coefficients, ref destination, yStride, residual, ((acMask >> block) & 1) != 0);
- }
-
- Unsafe.InitBlockUnaligned(ref Unsafe.As(ref coefficients), 0, 32);
+ ref byte plane = ref block < 20 ? ref du : ref dv;
+ InverseDctAdd(ref coefficients, ref Unsafe.Add(ref plane, ((block >> 1) & 1) * 4 * uvStride + (block & 1) * 4),
+ uvStride, residual, ((acMask >> block) & 1) != 0);
}
- }
- if ((nonzeroMask & 0xff0000) != 0)
- {
- for (int block = 16; block < 24; block++)
- {
- if (((nonzeroMask >> block) & 1) == 0)
- {
- continue;
- }
-
- ref short coefficients = ref Unsafe.Add(ref coefficientBase, block * 16);
- if (!skipResidual)
- {
- ref byte plane = ref block < 20 ? ref du : ref dv;
- InverseDctAdd(ref coefficients, ref Unsafe.Add(ref plane, ((block >> 1) & 1) * 4 * uvStride + (block & 1) * 4),
- uvStride, residual, ((acMask >> block) & 1) != 0);
- }
-
- Unsafe.InitBlockUnaligned(ref Unsafe.As(ref coefficients), 0, 32);
- }
+ Unsafe.InitBlockUnaligned(ref Unsafe.As(ref coefficients), 0, 32);
}
}
+ }
+ }
- if (!skipCopy)
- {
- // The next row predicts from this one's bottom row before the loop filter.
- MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref yRow0, 15 * yStride), paddedWidth)
- .CopyTo(MemoryMarshal.CreateSpan(ref topY, paddedWidth));
- MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref uRow0, 7 * uvStride), paddedWidth / 2)
- .CopyTo(MemoryMarshal.CreateSpan(ref topU, paddedWidth / 2));
- MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref vRow0, 7 * uvStride), paddedWidth / 2)
- .CopyTo(MemoryMarshal.CreateSpan(ref topV, paddedWidth / 2));
- }
+ ///
+ /// Completes the row decoded: keeps its unfiltered bottom rows for
+ /// the next row's prediction, loop-filters it, hands the rows that are now final to
+ /// and slides the cache. Returns true when the emitted rows reach
+ /// .
+ ///
+ public bool FinishRow(ref TSink sink, int rowLimit)
+ where TSink : IVp8RowSink, allows ref struct
+ {
+ bool skipCopy = (_ablation & WebpAblation.SkipMacroblockCopy) != 0;
+ int mbY = MacroblockY;
+ int yStride = _yStride;
+ int uvStride = _uvStride;
+ int paddedWidth = _paddedWidth;
+ if (!skipCopy)
+ {
+ // The next row predicts from this one's bottom row before the loop filter.
+ ref byte topY = ref MemoryMarshal.GetArrayDataReference(_topRows);
+ ref byte topU = ref Unsafe.Add(ref topY, paddedWidth);
+ ref byte topV = ref Unsafe.Add(ref topU, paddedWidth / 2);
+ ref byte yRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_yCache), LumaCacheExtra * yStride + CacheLeft);
+ ref byte uRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_uCache), ChromaCacheExtra * uvStride + CacheLeft);
+ ref byte vRow0 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_vCache), ChromaCacheExtra * uvStride + CacheLeft);
+ MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref yRow0, 15 * yStride), paddedWidth)
+ .CopyTo(MemoryMarshal.CreateSpan(ref topY, paddedWidth));
+ MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref uRow0, 7 * uvStride), paddedWidth / 2)
+ .CopyTo(MemoryMarshal.CreateSpan(ref topU, paddedWidth / 2));
+ MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref vRow0, 7 * uvStride), paddedWidth / 2)
+ .CopyTo(MemoryMarshal.CreateSpan(ref topV, paddedWidth / 2));
+ }
- if (applyLoopFilter)
- {
- FilterMacroblockRow(yCache, yStride, uCache, vCache, uvStride, mbWidth, mbY, filter, rowFilter);
- }
+ if ((_ablation & WebpAblation.SkipLoopFilter) == 0)
+ {
+ FilterMacroblockRow(_yCache, yStride, _uCache, _vCache, uvStride, MacroblockWidth, mbY, _filter, _rowFilter);
+ }
- int end = mbY == mbHeight - 1 ? height : mbY * 16 + 8;
- if ((ablation & WebpAblation.SkipOutput) == 0 && end > emitted)
- {
- sink.Emit(
- ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(yCache), CacheLeft), yStride, mbY * 16 - LumaCacheExtra,
- ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(uCache), CacheLeft),
- ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(vCache), CacheLeft),
- uvStride, mbY * 8 - ChromaCacheExtra, emitted, end);
- }
+ int end = mbY == MacroblockHeight - 1 ? _height : mbY * 16 + 8;
+ if ((_ablation & WebpAblation.SkipOutput) == 0 && end > Emitted)
+ {
+ sink.Emit(
+ ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_yCache), CacheLeft), yStride, mbY * 16 - LumaCacheExtra,
+ ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_uCache), CacheLeft),
+ ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_vCache), CacheLeft),
+ uvStride, mbY * 8 - ChromaCacheExtra, Emitted, end);
+ }
- emitted = end;
- if (emitted >= rowLimit)
- {
- break;
- }
+ Emitted = end;
+ MacroblockY = mbY + 1;
+ if (end >= rowLimit)
+ {
+ return true;
+ }
- // Slide the cache down by one macroblock row, keeping the rows the next row's loop
- // filter and output still need.
- if (!skipCopy)
- {
- yCache.AsSpan(16 * yStride, LumaCacheExtra * yStride).CopyTo(yCache);
- uCache.AsSpan(8 * uvStride, ChromaCacheExtra * uvStride).CopyTo(uCache);
- vCache.AsSpan(8 * uvStride, ChromaCacheExtra * uvStride).CopyTo(vCache);
- }
+ // Slide the cache down by one macroblock row, keeping the rows the next row's loop
+ // filter and output still need.
+ if (!skipCopy)
+ {
+ _yCache.AsSpan(16 * yStride, LumaCacheExtra * yStride).CopyTo(_yCache);
+ _uCache.AsSpan(8 * uvStride, ChromaCacheExtra * uvStride).CopyTo(_uCache);
+ _vCache.AsSpan(8 * uvStride, ChromaCacheExtra * uvStride).CopyTo(_vCache);
}
+
+ return false;
}
- finally
+
+ /// Returns every rented buffer; the state is unusable afterwards.
+ public void Dispose()
{
- WebpBufferPool.Return(yCache);
- WebpBufferPool.Return(uCache);
- WebpBufferPool.Return(vCache);
- WebpBufferPool.Return(topRows);
- WebpBufferPool.Return(aboveB);
- WebpBufferPool.Return(aboveNz);
- WebpBufferPool.Return(rowFilter);
- WebpBufferPool.Return(coefficientProbabilities);
- ReturnSegmentBuffers(segments);
- ReturnFilterBuffers(filter);
+ if (_yCache is null)
+ {
+ return;
+ }
+
+ WebpBufferPool.Return(_yCache);
+ WebpBufferPool.Return(_uCache);
+ WebpBufferPool.Return(_vCache);
+ WebpBufferPool.Return(_topRows);
+ WebpBufferPool.Return(_aboveB);
+ WebpBufferPool.Return(_aboveNz);
+ WebpBufferPool.Return(_rowFilter);
+ WebpBufferPool.Return(_probabilities);
+ if (_savedAboveB is not null)
+ {
+ WebpBufferPool.Return(_savedAboveB);
+ }
+
+ if (_savedAboveNz is not null)
+ {
+ WebpBufferPool.Return(_savedAboveNz);
+ }
+
+ ReturnSegmentBuffers(_segments);
+ ReturnFilterBuffers(_filter);
+ this = default;
}
}
@@ -1143,10 +1304,12 @@ private static int ReadTree(ref Vp8BoolDecoder decoder, ReadOnlySpan tree
}
}
- private static PartitionSlices ReadPartitions(ReadOnlySpan data, int count)
+ ///
+ /// The offset and length, within (everything after the first partition), of each of the
+ /// token partitions (RFC 6386 §9.5).
+ ///
+ internal static void ReadPartitionBounds(ReadOnlySpan data, int count, Span offsets, Span lengths)
{
- ReadOnlySpan p0 = default, p1 = default, p2 = default, p3 = default;
- ReadOnlySpan p4 = default, p5 = default, p6 = default, p7 = default;
int sizeCount = count - 1;
int tableLength = sizeCount * 3;
if (data.Length < tableLength)
@@ -1154,23 +1317,37 @@ private static PartitionSlices ReadPartitions(ReadOnlySpan data, int count
throw new InvalidDataException("The VP8 token partition size table is truncated.");
}
- Span sizes = stackalloc int[7];
- for (int i = 0; i < sizeCount; i++)
- {
- int sizeOffset = i * 3;
- sizes[i] = data[sizeOffset] | data[sizeOffset + 1] << 8 | data[sizeOffset + 2] << 16;
- }
-
int offset = tableLength;
for (int i = 0; i < count; i++)
{
- int size = i == sizeCount ? data.Length - offset : sizes[i];
+ int size = data.Length - offset;
+ if (i < sizeCount)
+ {
+ int sizeOffset = i * 3;
+ size = data[sizeOffset] | data[sizeOffset + 1] << 8 | data[sizeOffset + 2] << 16;
+ }
+
if (size > data.Length - offset)
{
throw new InvalidDataException("A VP8 token partition exceeds the frame.");
}
- ReadOnlySpan part = data.Slice(offset, size);
+ offsets[i] = offset;
+ lengths[i] = size;
+ offset += size;
+ }
+ }
+
+ private static PartitionSlices ReadPartitions(ReadOnlySpan data, int count)
+ {
+ ReadOnlySpan p0 = default, p1 = default, p2 = default, p3 = default;
+ ReadOnlySpan p4 = default, p5 = default, p6 = default, p7 = default;
+ Span offsets = stackalloc int[8];
+ Span lengths = stackalloc int[8];
+ ReadPartitionBounds(data, count, offsets, lengths);
+ for (int i = 0; i < count; i++)
+ {
+ ReadOnlySpan part = data.Slice(offsets[i], lengths[i]);
switch (i)
{
case 0: p0 = part; break;
@@ -1182,8 +1359,6 @@ private static PartitionSlices ReadPartitions(ReadOnlySpan data, int count
case 6: p6 = part; break;
case 7: p7 = part; break;
}
-
- offset += size;
}
return new PartitionSlices(p0, p1, p2, p3, p4, p5, p6, p7);
diff --git a/src/Sdcb.SimdCodecs.Webp/WebpDecoder.cs b/src/Sdcb.SimdCodecs.Webp/WebpDecoder.cs
index 388298f..a819dab 100644
--- a/src/Sdcb.SimdCodecs.Webp/WebpDecoder.cs
+++ b/src/Sdcb.SimdCodecs.Webp/WebpDecoder.cs
@@ -487,7 +487,7 @@ private static void DecodeLossyWithConcurrentAlpha(
}
/// An ALPH plane decoded on another thread, handed over once complete.
- private sealed class PendingAlpha
+ internal sealed class PendingAlpha
{
private byte[]? _plane;
@@ -555,8 +555,12 @@ private static void DecodeLossyRgba(
}
}
- /// Upsamples chroma (fancy or nearest) and converts finished rows to RGBA.
- private readonly ref struct RgbaSink(
+ ///
+ /// Upsamples chroma (fancy or nearest) and converts finished rows to RGBA: image row r goes to
+ /// output[(r - outputRow0) × stride] (a band of rows, for a streaming reader), its alpha comes from row r
+ /// of the whole plane.
+ ///
+ internal readonly ref struct RgbaSink(
Span output,
int stride,
int width,
@@ -565,7 +569,8 @@ private readonly ref struct RgbaSink(
ReadOnlySpan alpha,
ushort[] tRows,
byte[] chromaRows,
- PendingAlpha? pendingAlpha = null) : IVp8RowSink
+ PendingAlpha? pendingAlpha = null,
+ int outputRow0 = 0) : IVp8RowSink
{
private readonly Span _output = output;
private readonly ReadOnlySpan _alpha = alpha;
@@ -601,7 +606,7 @@ public void Emit(ref byte y, int yStride, int yRow0, ref byte u, ref byte v, int
ref byte uRow = ref Unsafe.Add(ref u, (chromaRow - uvRow0) * uvStride);
ref byte vRow = ref Unsafe.Add(ref v, (chromaRow - uvRow0) * uvStride);
ref byte yRow = ref Unsafe.Add(ref y, (row - yRow0) * yStride);
- ref byte destinationRow = ref Unsafe.Add(ref outputBase, row * stride);
+ ref byte destinationRow = ref Unsafe.Add(ref outputBase, (row - outputRow0) * stride);
ref byte alphaRow = ref Unsafe.NullRef();
if (hasAlpha)
{
@@ -1264,7 +1269,7 @@ private static void WritePixel(ref byte destination, int y, int u, int v, byte a
Unsafe.Add(ref destination, 3) = alpha;
}
- private static byte[] DecodeAndUnfilterAlpha(
+ internal static byte[] DecodeAndUnfilterAlpha(
ReadOnlySpan alphaChunk,
int width,
int height)
diff --git a/src/Sdcb.SimdCodecs.Webp/WebpImageDecoder.cs b/src/Sdcb.SimdCodecs.Webp/WebpImageDecoder.cs
index bac19b9..e77ccad 100644
--- a/src/Sdcb.SimdCodecs.Webp/WebpImageDecoder.cs
+++ b/src/Sdcb.SimdCodecs.Webp/WebpImageDecoder.cs
@@ -21,7 +21,7 @@ namespace Sdcb.SimdCodecs.Webp;
/// exactly the generic path's (whole decode, box filter, crop). Lossless and animated input take the generic path.
///
///
-public sealed class WebpImageDecoder : IMultiFrameImageDecoder
+public sealed class WebpImageDecoder : IMultiFrameImageDecoder, IStreamingImageDecoder
{
///
public static int SignatureLength => 12;
@@ -51,7 +51,7 @@ public static bool TryOpenFrames(ReadOnlyMemory data, [NotNullWhen(true)]
}
// WebP has no colour signalling besides its ICCP chunk: that profile's primaries, when H.273 names them.
- private static ColorEncoding EncodingOf(ReadOnlySpan iccProfile) =>
+ internal static ColorEncoding EncodingOf(ReadOnlySpan iccProfile) =>
IccPrimaries.Encoding(iccProfile) ?? ColorEncoding.AssumedSrgb;
///
@@ -327,6 +327,20 @@ public static bool TryReadMetadata(ReadOnlySpan data, [NotNullWhen(true)]
public static bool TryDecodeThumbnail(ReadOnlySpan data, [NotNullWhen(true)] out IDecodedImage? thumbnail) =>
ImageDecoderFallback.NoThumbnail(out thumbnail);
+ ///
+ ///
+ /// A lossy still (simple VP8, or VP8X with VP8 and optional ALPH) at full size streams: rows are decoded as the VP8
+ /// chunk's bytes arrive, with one token partition from a window of about two macroblock rows of compressed input
+ /// (O(width) memory), with several from the VP8 chunk buffered whole (O(compressed chunk) + O(width)). An ALPH plane
+ /// is decoded whole with the header (width × height bytes). Lossless, animated input and any other option read the
+ /// whole stream and decode it with ( false).
+ /// The rows equal 's byte for byte; lacks what is
+ /// stored after the image (an EXIF orientation, usually). An ALPH chunk after the VP8 chunk, or an animated VP8X
+ /// after it, which the span decoder applies, is refused with .
+ ///
+ public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) =>
+ new WebpRowReader(input, format, options);
+
/// The registration for ImageCodecs.Register, built from this type's method groups.
public static ImageDecoderRegistration Registration { get; } = new()
{
@@ -340,6 +354,7 @@ public static bool TryDecodeThumbnail(ReadOnlySpan data, [NotNullWhen(true
TryReadMetadata = TryReadMetadata,
TryDecodeThumbnail = TryDecodeThumbnail,
TryOpenFrames = TryOpenFrames,
+ CreateRowReader = CreateRowReader,
};
///
diff --git a/src/Sdcb.SimdCodecs.Webp/WebpRowReader.cs b/src/Sdcb.SimdCodecs.Webp/WebpRowReader.cs
new file mode 100644
index 0000000..364b972
--- /dev/null
+++ b/src/Sdcb.SimdCodecs.Webp/WebpRowReader.cs
@@ -0,0 +1,586 @@
+using System.Buffers;
+using System.Buffers.Binary;
+using Sdcb.SimdCodecs.Abstractions;
+using Sdcb.SimdCodecs.Abstractions.CodecSupport;
+
+namespace Sdcb.SimdCodecs.Webp;
+
+///
+/// The forward-only reader behind : a lossy still (simple VP8,
+/// or VP8X with VP8 and optional ALPH) decodes macroblock row by macroblock row as its bytes
+/// arrive; lossless, animated input and any option other than the whole image read the stream to its end and decode it
+/// with instead ( false).
+///
+/// The header reaches the VP8 chunk's first ten bytes, so every chunk before the image (ICCP, EXIF, ALPH, unknown ones)
+/// is buffered with it. The first partition (modes and probabilities, at most 512 KiB) is copied whole before the
+/// first row. With one token partition the rows then follow the token bytes: memory is that partition copy, the row
+/// caches and a window of compressed input about two macroblock rows long — O(width). With several partitions
+/// (macroblock row y reads partition y mod n, and they are stored one after another) the whole VP8 chunk is buffered
+/// before the first row (O(compressed chunk) + O(width)), the rows then come as asked. An ALPH plane is decoded whole
+/// with the header (width × height bytes).
+///
+///
+/// The rows are 's byte for byte: the same frame decoder, fed exactly the
+/// same bytes (a row whose token bytes have not all arrived is decoded again once they have), and the same RGBA → format
+/// conversion. The last row is held back until the container after the image has been checked to the RIFF end, so a
+/// file the span decoder refuses fails here too. Two container layouts the span decoder accepts are refused, because
+/// they change the image after its pixels: an ALPH chunk stored after the VP8 chunk, and a VP8X chunk after it that
+/// declares an animation. is 's except
+/// for chunks stored after the image (usually EXIF and XMP): their orientation, ICC profile or alpha flag is not in it.
+///
+///
+internal sealed class WebpRowReader : StreamingRowReader
+{
+ // The most rows one macroblock row's output spans: the last row, from the half row the one before held back.
+ private const int BandRows = 24;
+
+ private readonly DecodeOptions? _options;
+
+ // Header walk: DecodeHeader sees the same bytes from the file's start on every call, so it resumes here.
+ private long _walkOffset = 12;
+ private long _riffEnd;
+ private bool _extended;
+ private bool _alphaFlag;
+ private int _canvasWidth;
+ private int _canvasHeight;
+ private int _alphaOffset = -1;
+ private int _alphaLength;
+ private int _iccOffset = -1;
+ private int _iccLength;
+ private int _exifOffset = -1;
+ private int _exifLength;
+ private bool _hasXmp;
+ private bool _buffered;
+
+ // The VP8 chunk.
+ private int _width;
+ private int _height;
+ private int _vp8Length;
+ private long _vp8End; // file offset after the chunk and its pad byte
+ private int _firstPartitionLength;
+ private byte[]? _firstPartition;
+ private Vp8Decoder.FrameState _frame;
+ private bool _frameStarted;
+ private bool _frameDone;
+ private int _tokenLength; // bytes after the first partition
+ private int _tokenConsumed; // one partition: token bytes the decoder has read and the input consumed
+ private int _retryWindow; // one partition: token bytes to wait for before decoding a starved row again
+ private Cursor _header;
+ private Cursor[]? _partitions; // several partitions: one each
+ private Cursor _partitionState = Cursor.Fresh(0, 0); // one partition: its decoder state (the input holds its position)
+
+ // Output.
+ private byte[]? _alpha;
+ private byte[]? _band; // RGBA rows [_bandFirst, _bandEnd)
+ private ushort[]? _tRows;
+ private byte[]? _chromaRows;
+ private int _bandFirst;
+ private int _bandEnd;
+ private int _bandNext;
+
+ // The container after the image.
+ private long _trailerNext; // file offset of the next chunk header
+ private bool _trailerDone;
+
+ public WebpRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) : base(input, format) =>
+ _options = options;
+
+ /// A bool decoder between rows: the bytes it has read and its arithmetic state.
+ private struct Cursor
+ {
+ public int Start;
+ public int Length;
+ public int Used;
+ public ulong Value;
+ public int Bits;
+ public uint Range;
+
+ public static Cursor Fresh(int start, int length)
+ {
+ new Vp8BoolDecoder(default).Load(out ulong value, out int bits, out uint range);
+ return new Cursor { Start = start, Length = length, Value = value, Bits = bits, Range = range };
+ }
+
+ public readonly Vp8BoolDecoder Resume(ReadOnlySpan data) =>
+ new(data.Slice(Start + Used, Length - Used), Value, Bits, Range);
+
+ public void Save(in Vp8BoolDecoder decoder)
+ {
+ decoder.Load(out Value, out Bits, out Range);
+ Used = Length - decoder.Remaining;
+ }
+ }
+
+ protected override OperationStatus DecodeHeader(ReadOnlySpan input, bool isFinal, out int consumed,
+ out ImageInfo info, out int width, out int height)
+ {
+ consumed = 0;
+ info = default;
+ width = height = 0;
+ try
+ {
+ return ReadHeader(input, isFinal, out consumed, out info, out width, out height);
+ }
+ catch (Exception e) when (e is ArgumentException or NotSupportedException or OverflowException)
+ {
+ throw Invalid(e);
+ }
+ }
+
+ private OperationStatus ReadHeader(ReadOnlySpan input, bool isFinal, out int consumed,
+ out ImageInfo info, out int width, out int height)
+ {
+ consumed = 0;
+ info = default;
+ width = height = 0;
+ if (_buffered)
+ return ReadWhole(input, isFinal, out info, out width, out height);
+ if (input.Length < 12)
+ {
+ if (input.Length >= 4 && !input[..4].SequenceEqual("RIFF"u8))
+ throw new InvalidDataException("The data does not have a WebP RIFF header.");
+ return OperationStatus.NeedMoreData;
+ }
+
+ if (!WebpImageDecoder.CanDecode(input))
+ throw new InvalidDataException("The data does not have a WebP RIFF header.");
+ uint riffLength = BinaryPrimitives.ReadUInt32LittleEndian(input[4..8]);
+ if (riffLength < 4)
+ throw new InvalidDataException("The WebP RIFF size is invalid.");
+ _riffEnd = 8L + riffLength;
+
+ while (true)
+ {
+ long offset = _walkOffset;
+ if (offset >= _riffEnd)
+ throw new InvalidDataException("The WebP container has no valid image bitstream.");
+ if (_riffEnd - offset < 8)
+ throw new InvalidDataException("The WebP RIFF chunk header is truncated.");
+ if (input.Length - offset < 8)
+ return OperationStatus.NeedMoreData;
+
+ int at = (int)offset;
+ ReadOnlySpan type = input.Slice(at, 4);
+ uint chunkLength = BinaryPrimitives.ReadUInt32LittleEndian(input.Slice(at + 4, 4));
+ long payloadEnd = offset + 8 + chunkLength;
+ long next = payloadEnd + (chunkLength & 1);
+ if (next > _riffEnd)
+ throw new InvalidDataException("A WebP RIFF chunk exceeds the declared container size.");
+ if (chunkLength > int.MaxValue)
+ throw new InvalidDataException("A WebP RIFF chunk is longer than an array can hold.");
+ int length = (int)chunkLength;
+ int payload = at + 8;
+
+ if (type.SequenceEqual("VP8X"u8))
+ {
+ if (_extended || length < 10)
+ throw new InvalidDataException("The WebP VP8X chunk is invalid.");
+ if (input.Length - payload < 10)
+ return OperationStatus.NeedMoreData;
+ byte flags = input[payload];
+ if ((flags & 0x02) != 0)
+ return StartWhole(input, isFinal, out info, out width, out height);
+ _extended = true;
+ _alphaFlag = (flags & 0x10) != 0;
+ _canvasWidth = 1 + ReadUInt24(input.Slice(payload + 4, 3));
+ _canvasHeight = 1 + ReadUInt24(input.Slice(payload + 7, 3));
+ }
+ else if (type.SequenceEqual("VP8 "u8))
+ {
+ if (length < 10)
+ throw new InvalidDataException("The VP8 key-frame header is invalid or truncated.");
+ if (input.Length - payload < 10)
+ return OperationStatus.NeedMoreData;
+ return StartLossy(input, payload, length, isFinal, out consumed, out info, out width, out height);
+ }
+ else if (type.SequenceEqual("VP8L"u8) || type.SequenceEqual("ANIM"u8) || type.SequenceEqual("ANMF"u8))
+ {
+ // Lossless and animated images need the whole image (or file) before their first row.
+ return StartWhole(input, isFinal, out info, out width, out height);
+ }
+ else if (type.SequenceEqual("ALPH"u8))
+ {
+ if (_alphaOffset >= 0)
+ throw new InvalidDataException("The WebP contains more than one ALPH chunk.");
+ (_alphaOffset, _alphaLength) = (payload, length);
+ }
+ else if (type.SequenceEqual("ICCP"u8))
+ {
+ if (_iccOffset >= 0)
+ throw new InvalidDataException("The WebP contains more than one ICC profile.");
+ (_iccOffset, _iccLength) = (payload, length);
+ }
+ else if (type.SequenceEqual("EXIF"u8))
+ {
+ if (_exifOffset >= 0)
+ throw new InvalidDataException("The WebP contains more than one EXIF chunk.");
+ (_exifOffset, _exifLength) = (payload, length);
+ }
+ else if (type.SequenceEqual("XMP "u8))
+ {
+ if (_hasXmp)
+ throw new InvalidDataException("The WebP contains more than one XMP chunk.");
+ _hasXmp = true;
+ }
+
+ _walkOffset = next;
+ }
+ }
+
+ // A variant this reader does not stream: wait for the whole file, then let the span decoder have it.
+ private OperationStatus StartWhole(ReadOnlySpan input, bool isFinal, out ImageInfo info, out int width, out int height)
+ {
+ _buffered = true;
+ return ReadWhole(input, isFinal, out info, out width, out height);
+ }
+
+ private OperationStatus ReadWhole(ReadOnlySpan input, bool isFinal, out ImageInfo info, out int width, out int height)
+ {
+ info = default;
+ width = height = 0;
+ if (!isFinal)
+ return OperationStatus.NeedMoreData;
+ if (!WebpImageDecoder.TryReadInfo(input, out info))
+ throw new InvalidDataException("The WebP container is invalid.");
+ UseBufferedFallback(WebpImageDecoder.TryDecodeInto, _options);
+ (width, height) = (_options ?? DecodeOptions.Default).GetOutputSize(info);
+ return OperationStatus.Done;
+ }
+
+ // The VP8 chunk's first ten bytes are at input[payload]: the checks WebpContainer makes, then the streaming state.
+ private OperationStatus StartLossy(ReadOnlySpan input, int payload, int length, bool isFinal, out int consumed,
+ out ImageInfo info, out int width, out int height)
+ {
+ consumed = 0;
+ info = default;
+ width = height = 0;
+ ReadOnlySpan frame = input.Slice(payload, 10);
+ if ((frame[0] & 1) != 0 || frame[3] != 0x9d || frame[4] != 0x01 || frame[5] != 0x2a)
+ throw new InvalidDataException("The VP8 key-frame header is invalid or truncated.");
+ int imageWidth = BinaryPrimitives.ReadUInt16LittleEndian(frame.Slice(6, 2)) & 0x3fff;
+ int imageHeight = BinaryPrimitives.ReadUInt16LittleEndian(frame.Slice(8, 2)) & 0x3fff;
+ if (imageWidth == 0 || imageHeight == 0)
+ throw new InvalidDataException("The VP8 dimensions must be nonzero.");
+ int firstPartitionLength = (frame[0] | frame[1] << 8 | frame[2] << 16) >> 5;
+ if (firstPartitionLength > length - 10)
+ throw new InvalidDataException("The VP8 first partition exceeds the frame.");
+ if (!_extended)
+ (_canvasWidth, _canvasHeight) = (imageWidth, imageHeight);
+ else if (imageWidth != _canvasWidth || imageHeight != _canvasHeight)
+ throw new InvalidDataException(
+ $"The WebP VP8X canvas ({_canvasWidth}x{_canvasHeight}) does not match its image bitstream ({imageWidth}x{imageHeight}).");
+ if ((long)imageWidth * imageHeight > WebpLimits.MaximumPixels)
+ throw new InvalidDataException("The WebP dimensions exceed the supported pixel limit.");
+ if (!IsFullImage(_options))
+ return StartWhole(input, isFinal, out info, out width, out height);
+
+ bool hasAlpha = _alphaFlag || _alphaOffset >= 0;
+ ReadOnlySpan icc = _iccOffset >= 0 ? input.Slice(_iccOffset, _iccLength) : default;
+ info = new ImageInfo(imageWidth, imageHeight, hasAlpha ? 4 : 3, SampleFormat.UInt8)
+ {
+ Format = ImageFormat.Webp,
+ Orientation = _exifOffset >= 0 ? ExifOrientation.Read(input.Slice(_exifOffset, _exifLength)) : ImageOrientation.Normal,
+ FrameCount = 1,
+ ColorEncoding = WebpImageDecoder.EncodingOf(icc),
+ };
+
+ // The ALPH chunk is buffered (it precedes this one) and is consumed with the header: decode it now.
+ if (_alphaOffset >= 0)
+ _alpha = WebpDecoder.DecodeAndUnfilterAlpha(input.Slice(_alphaOffset, _alphaLength), imageWidth, imageHeight);
+
+ (_width, _height) = (imageWidth, imageHeight);
+ _vp8Length = length;
+ _vp8End = payload + (long)length + (length & 1);
+ _firstPartitionLength = firstPartitionLength;
+ int rgbaRow = checked(imageWidth * 4);
+ _band = WebpBufferPool.Rent(checked(rgbaRow * BandRows));
+ _tRows = WebpBufferPool.Rent(checked(((imageWidth + 1) >> 1) * 2));
+ _chromaRows = WebpBufferPool.Rent(checked(imageWidth * 2));
+ consumed = payload;
+ (width, height) = (imageWidth, imageHeight);
+ return OperationStatus.Done;
+ }
+
+ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed,
+ Span destination, int stride, int rowCount, out int rowsWritten)
+ {
+ consumed = 0;
+ rowsWritten = 0;
+ try
+ {
+ while (true)
+ {
+ while (_bandNext < _bandEnd && rowsWritten < rowCount)
+ {
+ // The last row waits for the rest of the container: a file the span decoder refuses fails here.
+ if (_bandNext == _height - 1 && !_trailerDone && !ReadTrailer(input, isFinal, ref consumed))
+ return OperationStatus.NeedMoreData;
+ WriteRow(_bandNext, destination.Slice(rowsWritten * stride));
+ _bandNext++;
+ rowsWritten++;
+ }
+
+ if (rowsWritten == rowCount)
+ return OperationStatus.Done;
+
+ // RGBA rows the caller asked for go straight into its buffer, skipping the band copy; the image's
+ // last row never does (it waits for the container check).
+ Span direct = default;
+ if (_frameStarted && Format == PixelFormat.Rgba32)
+ {
+ int end = _frame.MacroblockY == _frame.MacroblockHeight - 1 ? _height : _frame.MacroblockY * 16 + 8;
+ if (end < _height && end - _frame.Emitted <= rowCount - rowsWritten)
+ direct = destination[(rowsWritten * stride)..];
+ }
+
+ if (!DecodeMacroblockRow(input, isFinal, ref consumed, direct, stride, ref rowsWritten))
+ return OperationStatus.NeedMoreData;
+ }
+ }
+ catch (Exception e) when (e is ArgumentException or NotSupportedException or OverflowException)
+ {
+ throw Invalid(e);
+ }
+ }
+
+ // Decodes the next macroblock row into the band (or, first, reads the frame header). False when the input ends
+ // inside what it needs; nothing is consumed or changed then.
+ // A non-empty direct takes the row's output (RGBA, at directStride), counted in rowsWritten, instead of the band.
+ private bool DecodeMacroblockRow(ReadOnlySpan input, bool isFinal, ref int consumed, Span direct,
+ int directStride, ref int rowsWritten)
+ {
+ ReadOnlySpan data = input[consumed..];
+ if (!_frameStarted)
+ {
+ int headerBytes = 10 + _firstPartitionLength;
+ if (data.Length < headerBytes)
+ return Starved(isFinal);
+ Vp8Decoder.ReadFrameTag(data, _vp8Length, _width, _height);
+ _firstPartition = WebpBufferPool.Rent(Math.Max(_firstPartitionLength, 1));
+ data.Slice(10, _firstPartitionLength).CopyTo(_firstPartition);
+ var header = new Vp8BoolDecoder(_firstPartition.AsSpan(0, _firstPartitionLength));
+ _frame = Vp8Decoder.FrameState.Create(ref header, _width, _height, WebpAblation.None);
+ _frameStarted = true;
+ _header = Cursor.Fresh(0, _firstPartitionLength);
+ _header.Save(header);
+ _tokenLength = _vp8Length - headerBytes;
+ consumed += headerBytes;
+ return true;
+ }
+
+ if (_frame.PartitionCount == 1)
+ {
+ int left = _tokenLength - _tokenConsumed;
+ int available = Math.Min(data.Length, left);
+ bool complete = available == left;
+ if (!complete)
+ {
+ if (isFinal)
+ throw Truncated();
+ if (available < _retryWindow)
+ return false;
+ }
+
+ var header = _header.Resume(_firstPartition!);
+ var tokens = new Vp8BoolDecoder(data[..available], _partitionState.Value, _partitionState.Bits, _partitionState.Range);
+ _frame.SaveContexts();
+ // Over a window that ends before the partition does, zero bits past it are not the stream's: a row that
+ // read them is decoded again once more of the partition is there. A starved row costs its decode time,
+ // so the next attempt waits for twice the window.
+ _frame.ReconstructRow(ref header, ref tokens);
+ if (!complete && tokens.Padded)
+ {
+ _frame.RestoreContexts();
+ _retryWindow = (int)Math.Min((long)available * 2 + 64, int.MaxValue);
+ return false;
+ }
+
+ _header.Save(header);
+ tokens.Load(out _partitionState.Value, out _partitionState.Bits, out _partitionState.Range);
+ int used = available - tokens.Remaining;
+ _tokenConsumed += used;
+ consumed += used;
+ _retryWindow = 0;
+ }
+ else
+ {
+ // Several partitions: the whole chunk first (row y reads partition y mod n), never consumed until the end.
+ if (data.Length < _tokenLength)
+ return Starved(isFinal);
+ ReadOnlySpan tokenData = data[.._tokenLength];
+ int count = _frame.PartitionCount;
+ if (_partitions is null)
+ {
+ Span offsets = stackalloc int[8];
+ Span lengths = stackalloc int[8];
+ Vp8Decoder.ReadPartitionBounds(tokenData, count, offsets, lengths);
+ var partitions = new Cursor[count];
+ for (int i = 0; i < count; i++)
+ partitions[i] = Cursor.Fresh(offsets[i], lengths[i]);
+ _partitions = partitions;
+ }
+
+ ref Cursor cursor = ref _partitions[_frame.MacroblockY & (count - 1)];
+ var header = _header.Resume(_firstPartition!);
+ var tokens = cursor.Resume(tokenData);
+ _frame.ReconstructRow(ref header, ref tokens);
+ _header.Save(header);
+ cursor.Save(tokens);
+ }
+
+ int first = _frame.Emitted;
+ ReadOnlySpan alpha = _alpha is null ? default : _alpha.AsSpan(0, _width * _height);
+ if (direct.IsEmpty)
+ {
+ var sink = new WebpDecoder.RgbaSink(_band, _width * 4, _width, _height, fancy: true, alpha, _tRows!, _chromaRows!,
+ outputRow0: first);
+ _frame.FinishRow(ref sink, int.MaxValue);
+ (_bandFirst, _bandEnd, _bandNext) = (first, _frame.Emitted, first);
+ }
+ else
+ {
+ // DecodeRows chose direct only when the rows this macroblock row emits, [first, end), fit the rows left
+ // in the request, and the base checked the destination for all of those at directStride: every row
+ // the sink writes (it indexes from first) is inside direct.
+ var sink = new WebpDecoder.RgbaSink(direct, directStride, _width, _height, fancy: true, alpha, _tRows!,
+ _chromaRows!, outputRow0: first);
+ _frame.FinishRow(ref sink, int.MaxValue);
+ rowsWritten += _frame.Emitted - first;
+ (_bandFirst, _bandEnd, _bandNext) = (_frame.Emitted, _frame.Emitted, _frame.Emitted);
+ }
+ if (_frame.MacroblockY == _frame.MacroblockHeight)
+ {
+ _frame.Dispose();
+ _frameDone = true;
+ _trailerNext = _vp8End;
+ }
+
+ return true;
+ }
+
+
+ private static bool Starved(bool isFinal) => isFinal ? throw Truncated() : false;
+
+ private static InvalidDataException Truncated() => new("The WebP stream ends inside its VP8 chunk.");
+
+ // Skips the rest of the VP8 chunk and walks the chunks after it to the RIFF end, applying WebpContainer's rules.
+ // True once at the end; false when the input ends first.
+ private bool ReadTrailer(ReadOnlySpan input, bool isFinal, ref int consumed)
+ {
+ while (true)
+ {
+ long at = Input.Position + consumed;
+ if (at < _trailerNext)
+ {
+ int skip = (int)Math.Min(_trailerNext - at, input.Length - consumed);
+ consumed += skip;
+ at += skip;
+ if (at < _trailerNext)
+ return isFinal ? throw new InvalidDataException("The WebP RIFF size exceeds the supplied data.") : false;
+ }
+
+ if (_trailerNext == _riffEnd)
+ {
+ _trailerDone = true;
+ return true;
+ }
+
+ if (_riffEnd - _trailerNext < 8)
+ throw new InvalidDataException("The WebP RIFF chunk header is truncated.");
+ ReadOnlySpan chunk = input[consumed..];
+ if (chunk.Length < 8)
+ return isFinal ? throw new InvalidDataException("The WebP RIFF size exceeds the supplied data.") : false;
+ ReadOnlySpan type = chunk[..4];
+ uint chunkLength = BinaryPrimitives.ReadUInt32LittleEndian(chunk.Slice(4, 4));
+ long next = _trailerNext + 8 + chunkLength + (chunkLength & 1);
+ if (next > _riffEnd)
+ throw new InvalidDataException("A WebP RIFF chunk exceeds the declared container size.");
+ if (chunkLength > int.MaxValue)
+ throw new InvalidDataException("A WebP RIFF chunk is longer than an array can hold.");
+
+ if (type.SequenceEqual("VP8 "u8) || type.SequenceEqual("VP8L"u8))
+ throw new InvalidDataException("The WebP contains more than one image bitstream.");
+ if (type.SequenceEqual("ALPH"u8))
+ throw new InvalidDataException(_alphaOffset >= 0
+ ? "The WebP contains more than one ALPH chunk."
+ : "The WebP stores its ALPH chunk after the image bitstream, which a streaming decoder cannot apply.");
+ if (type.SequenceEqual("ANIM"u8) || type.SequenceEqual("ANMF"u8))
+ throw new InvalidDataException("The WebP has animation chunks without the VP8X animation flag.");
+ if (type.SequenceEqual("VP8X"u8))
+ {
+ if (_extended || chunkLength < 10)
+ throw new InvalidDataException("The WebP VP8X chunk is invalid.");
+ if (chunk.Length < 18)
+ return isFinal ? throw new InvalidDataException("The WebP RIFF size exceeds the supplied data.") : false;
+ if ((chunk[8] & 0x02) != 0)
+ throw new InvalidDataException(
+ "The WebP stores an animated VP8X chunk after the image bitstream, which a streaming decoder cannot apply.");
+ if (1 + ReadUInt24(chunk.Slice(12, 3)) != _width || 1 + ReadUInt24(chunk.Slice(15, 3)) != _height)
+ throw new InvalidDataException("The WebP VP8X canvas does not match its image bitstream.");
+ _extended = true;
+ }
+ else if (type.SequenceEqual("ICCP"u8))
+ {
+ if (_iccOffset >= 0)
+ throw new InvalidDataException("The WebP contains more than one ICC profile.");
+ _iccOffset = int.MaxValue;
+ }
+ else if (type.SequenceEqual("EXIF"u8))
+ {
+ if (_exifOffset >= 0)
+ throw new InvalidDataException("The WebP contains more than one EXIF chunk.");
+ _exifOffset = int.MaxValue;
+ }
+ else if (type.SequenceEqual("XMP "u8))
+ {
+ if (_hasXmp)
+ throw new InvalidDataException("The WebP contains more than one XMP chunk.");
+ _hasXmp = true;
+ }
+
+ consumed += 8;
+ _trailerNext = next;
+ }
+ }
+
+ private void WriteRow(int row, Span destination)
+ {
+ int rgbaRow = _width * 4;
+ ReadOnlySpan source = _band.AsSpan((row - _bandFirst) * rgbaRow, rgbaRow);
+ if (Format == PixelFormat.Rgba32)
+ source.CopyTo(destination);
+ else
+ PixelConverter.ConvertRow(source, PixelFormat.Rgba32, destination, Format, _width);
+ }
+
+ private static int ReadUInt24(ReadOnlySpan data) => data[0] | (data[1] << 8) | (data[2] << 16);
+
+ private static InvalidDataException Invalid(Exception e) =>
+ new(e is NotSupportedException ? $"The WebP uses a feature this decoder does not support: {e.Message}"
+ : $"The WebP data is invalid: {e.Message}", e);
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (_frameStarted && !_frameDone)
+ _frame.Dispose();
+ ReturnTo(ref _firstPartition);
+ ReturnTo(ref _alpha);
+ ReturnTo(ref _band);
+ ReturnTo(ref _chromaRows);
+ if (_tRows is not null)
+ WebpBufferPool.Return(_tRows);
+ _tRows = null;
+ }
+
+ base.Dispose(disposing);
+ }
+
+ private static void ReturnTo(ref byte[]? buffer)
+ {
+ if (buffer is not null)
+ WebpBufferPool.Return(buffer);
+ buffer = null;
+ }
+}
diff --git a/tests/Sdcb.SimdCodecs.Tests/WebpStreamingDecodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/WebpStreamingDecodeTests.cs
new file mode 100644
index 0000000..5c2d432
--- /dev/null
+++ b/tests/Sdcb.SimdCodecs.Tests/WebpStreamingDecodeTests.cs
@@ -0,0 +1,397 @@
+using System.Buffers.Binary;
+using ImageMagick;
+using Sdcb.SimdCodecs.Abstractions;
+using Sdcb.SimdCodecs.Abstractions.CodecSupport;
+using Sdcb.SimdCodecs.Tests.Streaming;
+using Sdcb.SimdCodecs.Webp;
+using Shouldly;
+
+namespace Sdcb.SimdCodecs.Tests;
+
+///
+/// : a lossy still streams (one token partition from a window of the
+/// input, several from the buffered chunk), everything else falls back; either way the rows equal
+/// 's — and so, where the goldens and oracle tests pin those, libwebp's —
+/// under every feed, and a file the span decoder refuses fails with .
+///
+public sealed class WebpStreamingDecodeTests
+{
+ private static readonly string FixtureDirectory = Path.Combine(AppContext.BaseDirectory, "Fixtures", "webp");
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+ private static ImageDecoderRegistration Codec => WebpImageDecoder.Registration;
+
+ private static readonly PixelFormat[] Formats =
+ [
+ PixelFormat.Rgba32, PixelFormat.Bgra32, PixelFormat.Rgb24, PixelFormat.Bgr24, PixelFormat.Gray8,
+ PixelFormat.GrayAlpha16, PixelFormat.Rgba64, PixelFormat.Gray16, PixelFormat.Rgba32Premultiplied,
+ PixelFormat.Bgra32Premultiplied,
+ ];
+
+ public static TheoryData Fixtures()
+ {
+ var data = new TheoryData();
+ foreach (var path in Directory.GetFiles(FixtureDirectory, "*.webp").Order())
+ data.Add(Path.GetFileName(path));
+ data.Add("magick:rgba");
+ data.Add("magick:tall");
+ data.Add("encoder:wide");
+ return data;
+ }
+
+ private static byte[] Load(string name) => name switch
+ {
+ "magick:rgba" => MagickLossy(171, 99, alpha: true),
+ "magick:tall" => MagickLossy(37, 530, alpha: false),
+ "encoder:wide" => EncodeLossy(611, 75, seed: 3, alpha: true),
+ _ => File.ReadAllBytes(Path.Combine(FixtureDirectory, name)),
+ };
+
+ // Foreign bytes: a lossy WebP written by ImageMagick (libwebp's encoder inside) from a gradient with noise.
+ private static byte[] MagickLossy(int width, int height, bool alpha)
+ {
+ var channels = alpha ? 4 : 3;
+ var pixels = new byte[width * height * channels];
+ var rng = new Random(width * 7919 + height);
+ for (var i = 0; i < pixels.Length; i++)
+ pixels[i] = (byte)((i / channels % width) * 255 / width ^ rng.Next(0, 40));
+ using var image = new MagickImage();
+ image.ReadPixels(pixels, new PixelReadSettings((uint)width, (uint)height, StorageType.Char, alpha ? "RGBA" : "RGB"));
+ image.Quality = 70;
+ image.Settings.SetDefine(MagickFormat.WebP, "lossless", false);
+ return image.ToByteArray(MagickFormat.WebP);
+ }
+
+ private static byte[] EncodeLossy(int width, int height, int seed, bool alpha, int quality = 60)
+ {
+ var pixels = new byte[width * height * 4];
+ var rng = new Random(seed);
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ var i = (y * width + x) * 4;
+ pixels[i] = (byte)(x * 3 + rng.Next(0, 16));
+ pixels[i + 1] = (byte)(y * 5 ^ x);
+ pixels[i + 2] = (byte)((x + y) * 2);
+ pixels[i + 3] = alpha ? (byte)(x * y % 256) : (byte)255;
+ }
+ }
+ return WebpEncoder.EncodeLossy(pixels, width, height, PixelFormat.Rgba32,
+ new WebpLossyEncodeOptions { Quality = quality, Effort = 0 });
+ }
+
+ private static bool Streams(byte[] file) => WebpDecoder.ReadInfo(file) is { Format: WebpFormat.Lossy };
+
+ [Theory]
+ [MemberData(nameof(Fixtures))]
+ public void Rows_equal_TryDecodeInto_for_every_format_and_feed(string fixture)
+ {
+ var file = Load(fixture);
+ var streams = Streams(file);
+ foreach (var format in Formats)
+ {
+ // One byte per read is slow; it runs on the default format only.
+ var feeds = format == PixelFormat.Rgba32 ? StreamingAssert.AllFeeds
+ : [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly, StreamingAssert.Feed.Whole];
+ StreamingAssert.RowsEqualDecodeInto(Codec, file, format, expectStreaming: streams, feeds: feeds);
+ }
+ }
+
+ [Theory]
+ [InlineData("noise-64x48-vp8-partitions2.webp")]
+ [InlineData("noise-64x48-vp8-partitions4.webp")]
+ [InlineData("noise-64x48-vp8-partitions8.webp")]
+ [InlineData("lossy-alpha-q50.webp")]
+ [InlineData("testsrc2-320x240-q75.webp")]
+ public void Lossy_stills_stream(string fixture)
+ {
+ var file = Load(fixture);
+ Streams(file).ShouldBeTrue();
+ StreamingAssert.RowsEqualDecodeInto(Codec, file, PixelFormat.Rgba32, expectStreaming: true,
+ feeds: [StreamingAssert.Feed.RandomChunks]);
+ }
+
+ [Theory]
+ [InlineData("lossless-z6.webp")]
+ [InlineData("anim-img2webp-lossy.webp")]
+ [InlineData("anim-webpmux-metadata.webp")]
+ public void Lossless_and_animated_input_fall_back(string fixture)
+ {
+ var file = Load(fixture);
+ StreamingAssert.RowsEqualDecodeInto(Codec, file, PixelFormat.Rgba32, expectStreaming: false,
+ feeds: [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly]);
+ }
+
+ [Fact]
+ public void Options_other_than_the_whole_image_fall_back()
+ {
+ var file = Load("testsrc2-320x240-q75.webp");
+ StreamingAssert.RowsEqualDecodeInto(Codec, file, PixelFormat.Rgb24, new DecodeOptions { ScaleDenominator = 2 },
+ expectStreaming: false, feeds: [StreamingAssert.Feed.RandomChunks]);
+ StreamingAssert.RowsEqualDecodeInto(Codec, file, PixelFormat.Rgba32,
+ new DecodeOptions { Region = new PixelRect(5, 17, 100, 61) }, expectStreaming: false,
+ feeds: [StreamingAssert.Feed.AsyncOnly]);
+ }
+
+ [Theory]
+ [InlineData("webp-metadata.webp")]
+ [InlineData("lossy-alpha-q50.webp")]
+ [InlineData("testsrc2-320x240-q75.webp")]
+ public void Info_is_TryReadInfo_for_chunks_before_the_image(string fixture)
+ {
+ var file = Load(fixture);
+ WebpImageDecoder.TryReadInfo(file, out var expected).ShouldBeTrue();
+ using var reader = WebpImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(file, 64)), PixelFormat.Rgba32, null);
+ reader.Initialize(Ct);
+ var info = reader.Info;
+ (info.Width, info.Height, info.Channels, info.Format, info.FrameCount).ShouldBe(
+ (expected.Width, expected.Height, expected.Channels, expected.Format, expected.FrameCount));
+ info.ColorEncoding.ShouldBe(expected.ColorEncoding);
+ }
+
+ [Fact]
+ public async Task End_to_end_async_only_stream_equals_TryDecodeInto_and_dwebp_goldens()
+ {
+ // lossy-alpha-q50.webp is in webp-oracle-golden.tsv, so TryDecodeInto's RGBA is libwebp 1.6.0's.
+ var path = Path.Combine(FixtureDirectory, "lossy-alpha-q50.webp");
+ var file = await File.ReadAllBytesAsync(path, Ct);
+ WebpImageDecoder.TryReadInfo(file, out var info).ShouldBeTrue();
+ var expected = new byte[info.Width * info.Height * 4];
+ WebpImageDecoder.TryDecodeInto(file, expected, 0, PixelFormat.Rgba32, cancellationToken: Ct).ShouldBeTrue();
+
+ foreach (var make in new Func[]
+ {
+ () => new ChunkedStream(file, maxChunk: 61, asyncOnly: true),
+ () => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 512, useAsync: true),
+ })
+ {
+ await using var reader = Codec.CreateRowReader!(new StreamInput(make(), initialCapacity: 16), PixelFormat.Rgba32, null);
+ await reader.InitializeAsync(Ct);
+ reader.IsStreaming.ShouldBeTrue();
+ var actual = new byte[expected.Length];
+ var rowBytes = info.Width * 4;
+ while (reader.RowsRead < reader.Height)
+ (await reader.ReadRowsAsync(actual.AsMemory(reader.RowsRead * rowBytes), 5, 0, Ct)).ShouldBeGreaterThan(0);
+ actual.ShouldBe(expected);
+ }
+ }
+
+ [Fact]
+ public void First_rows_read_only_a_prefix()
+ {
+ var file = EncodeLossy(512, 512, seed: 9, alpha: false);
+ var stream = new ChunkedStream(file, maxChunk: 256);
+ using var reader = WebpImageDecoder.CreateRowReader(new StreamInput(stream, initialCapacity: 16), PixelFormat.Rgba32, null);
+ var band = new byte[512 * 4 * 16];
+ reader.ReadRows(band, 16, 0, Ct).ShouldBe(16);
+ reader.IsStreaming.ShouldBeTrue();
+ stream.BytesRead.ShouldBeLessThan(file.Length / 4, $"read {stream.BytesRead} of {file.Length} bytes for 16 of 512 rows");
+ }
+
+ private static readonly Lazy Huge = new(() => EncodeLossy(8192, 8192, seed: 5, alpha: false, quality: 30));
+
+ [Fact]
+ public void A_large_single_partition_image_streams_in_bounded_memory()
+ {
+ var file = Huge.Value;
+ const int width = 8192;
+ var band = new byte[width * 4 * 16];
+ long peakWindow = 0;
+ StreamingAssert.AllocatesLessThan(1 << 20, () =>
+ {
+ var stream = new ChunkedStream(file, maxChunk: 64 * 1024);
+ using var reader = WebpImageDecoder.CreateRowReader(new StreamInput(stream, initialCapacity: 4096), PixelFormat.Rgba32, null);
+ reader.Initialize(Ct);
+ reader.IsStreaming.ShouldBeTrue();
+ while (reader.RowsRead < reader.Height)
+ {
+ var rows = reader.RowsRead;
+ reader.ReadRows(band, 16, 0, Ct).ShouldBeGreaterThan(0);
+ if (rows == 0)
+ peakWindow = stream.BytesRead;
+ }
+ }, "8192x8192 streamed decode");
+ // The whole image is 256 MiB of RGBA; the first band needed a small part of the file.
+ peakWindow.ShouldBeLessThan(file.Length / 8);
+ }
+
+ [Theory]
+ [InlineData("lossy-alpha-q50.webp")]
+ [InlineData("noise-64x48-vp8-partitions4.webp")]
+ [InlineData("webp-metadata.webp")]
+ [InlineData("odd-33x19-libvpx.webp")]
+ public void A_truncated_stream_fails_where_TryDecodeInto_does(string fixture)
+ {
+ var file = Load(fixture);
+ WebpImageDecoder.TryReadInfo(file, out var info).ShouldBeTrue();
+ var buffer = new byte[info.Width * info.Height * 4];
+ for (var cut = 0; cut < file.Length; cut += Math.Max(1, file.Length / 97))
+ {
+ var truncated = file[..cut];
+ WebpImageDecoder.TryDecodeInto(truncated, buffer, 0, PixelFormat.Rgba32, cancellationToken: Ct).ShouldBeFalse();
+ Should.Throw(() => StreamingAssert.ReadAll(truncated, StreamingAssert.Feed.RandomChunks,
+ input => WebpImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _), $"cut at {cut}");
+ }
+ }
+
+ [Theory]
+ [InlineData("testsrc2-320x240-q75.webp")]
+ [InlineData("lossy-alpha-q50.webp")]
+ [InlineData("noise-64x48-vp8-partitions2.webp")]
+ public void A_short_token_partition_decodes_as_the_span_decoder_does(string fixture)
+ {
+ // The chunk and RIFF sizes say the image ends early: the span decoder reads zero bits past its partitions'
+ // end, and so must the streaming one, at the same place.
+ var file = Load(fixture);
+ var vp8 = FindChunk(file, "VP8 "u8);
+ var length = BinaryPrimitives.ReadInt32LittleEndian(file.AsSpan(vp8 + 4));
+ var firstPartition = (file[vp8 + 8] | file[vp8 + 9] << 8 | file[vp8 + 10] << 16) >> 5;
+ var tokens = length - 10 - firstPartition;
+ foreach (var drop in new[] { 1, 2, 7, 8, 9, tokens / 3, tokens / 2, tokens - 30 })
+ {
+ if (drop <= 0 || drop >= tokens) continue;
+ var shortened = Shorten(file, vp8, length, drop);
+ var buffer = new byte[4 << 20];
+ if (WebpImageDecoder.TryDecodeInto(shortened, buffer, 0, PixelFormat.Rgba32, cancellationToken: Ct))
+ StreamingAssert.RowsEqualDecodeInto(Codec, shortened, PixelFormat.Rgba32, expectStreaming: true,
+ feeds: [StreamingAssert.Feed.OneByte, StreamingAssert.Feed.RandomChunks]);
+ else
+ Should.Throw(() => StreamingAssert.ReadAll(shortened, StreamingAssert.Feed.RandomChunks,
+ input => WebpImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _));
+ }
+ }
+
+ [Fact]
+ public void A_late_alpha_chunk_is_refused()
+ {
+ // A simple-format file with an ALPH chunk after its VP8 chunk: the span decoder applies it, a streaming
+ // decoder has emitted the rows by then, so it refuses the file instead of returning different pixels.
+ var file = Load("testsrc2-320x240-q75.webp");
+ var alpha = new byte[8 + 1 + 320 * 240];
+ "ALPH"u8.CopyTo(alpha);
+ BinaryPrimitives.WriteInt32LittleEndian(alpha.AsSpan(4), 1 + 320 * 240);
+ alpha.AsSpan(9).Fill(77);
+ var late = file.Concat(alpha).Concat(new byte[alpha.Length & 1]).ToArray();
+ BinaryPrimitives.WriteInt32LittleEndian(late.AsSpan(4), late.Length - 8);
+ WebpImageDecoder.TryDecodeInto(late, new byte[320 * 240 * 4], 0, PixelFormat.Rgba32, cancellationToken: Ct).ShouldBeTrue();
+ Should.Throw(() => StreamingAssert.ReadAll(late, StreamingAssert.Feed.Whole,
+ input => WebpImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _));
+ }
+
+ [Fact]
+ public void Streaming_fuzz()
+ {
+ var iterations = int.TryParse(Environment.GetEnvironmentVariable("WEBP_STREAM_FUZZ_ITERATIONS"), out var n) ? n : 1500;
+ var seeds = new[]
+ {
+ Load("lossy-alpha-q50.webp"), Load("noise-64x48-vp8-partitions4.webp"), Load("webp-metadata.webp"),
+ Load("noise-32x32-segments4.webp"), Load("odd-33x19-libvpx.webp"), Load("tiny.webp"), Load("lossless-3x7.webp"),
+ };
+ var rng = new Random(20261123);
+ var buffer = new byte[1 << 22];
+ for (var i = 0; i < iterations; i++)
+ {
+ Ct.ThrowIfCancellationRequested();
+ var file = Mutate(seeds[rng.Next(seeds.Length)], rng);
+ // A mutated header can declare a canvas of up to 2^26 pixels: such files are not compared (ReadAll would
+ // allocate the whole canvas), only those small enough for the buffer.
+ if (WebpImageDecoder.TryReadInfo(file, out var info) && (long)info.Width * info.Height * 4 > buffer.Length)
+ continue;
+ var spanOk = WebpImageDecoder.TryDecodeInto(file, buffer, 0, PixelFormat.Rgba32, cancellationToken: Ct);
+ byte[] rows;
+ try
+ {
+ rows = StreamingAssert.ReadAll(file, StreamingAssert.Feed.RandomChunks,
+ input => WebpImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _, seed: i);
+ }
+ catch (InvalidDataException) when (!spanOk || HasLateImageChunk(file))
+ {
+ continue;
+ }
+
+ spanOk.ShouldBeTrue($"iteration {i}: the stream decoded a file TryDecodeInto refuses " +
+ $"({Convert.ToHexString(file.AsSpan(0, Math.Min(64, file.Length)))})");
+ rows.AsSpan().SequenceEqual(buffer.AsSpan(0, rows.Length)).ShouldBeTrue($"iteration {i}: rows differ");
+ }
+ }
+
+ private static byte[] Mutate(byte[] seed, Random rng)
+ {
+ var file = (byte[])seed.Clone();
+ switch (rng.Next(5))
+ {
+ case 0: // flip bytes
+ for (var k = rng.Next(1, 6); k > 0; k--)
+ file[rng.Next(file.Length)] ^= (byte)rng.Next(1, 256);
+ return file;
+ case 1: // truncate
+ return file[..rng.Next(file.Length)];
+ case 2: // flip a byte inside the token data only, so the container stays valid
+ file[rng.Next(Math.Min(file.Length - 1, 40), file.Length)] = (byte)rng.Next(256);
+ return file;
+ case 3: // flip a length field
+ {
+ var at = rng.Next(4) switch { 0 => 4, 1 => 16, _ => rng.Next(12, Math.Max(13, file.Length - 4)) };
+ if (at + 4 <= file.Length)
+ BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(at), (uint)rng.Next(0, file.Length + 64));
+ return file;
+ }
+ default: // append a random chunk and fix the RIFF size
+ {
+ string[] types = ["EXIF", "XMP ", "ICCP", "ALPH", "VP8X", "ANIM", "ANMF", "abcd", "VP8 "];
+ var payload = new byte[rng.Next(0, 24)];
+ rng.NextBytes(payload);
+ var chunk = new byte[8 + payload.Length + (payload.Length & 1)];
+ System.Text.Encoding.ASCII.GetBytes(types[rng.Next(types.Length)]).CopyTo(chunk, 0);
+ BinaryPrimitives.WriteInt32LittleEndian(chunk.AsSpan(4), payload.Length);
+ payload.CopyTo(chunk, 8);
+ var grown = file.Concat(chunk).ToArray();
+ if (grown.Length >= 8)
+ BinaryPrimitives.WriteInt32LittleEndian(grown.AsSpan(4), grown.Length - 8);
+ return grown;
+ }
+ }
+ }
+
+ // The two layouts the streaming reader refuses although the span decoder may accept them.
+ private static bool HasLateImageChunk(byte[] file)
+ {
+ var sawImage = false;
+ for (var offset = 12; offset + 8 <= file.Length;)
+ {
+ var type = file.AsSpan(offset, 4);
+ var length = BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(offset + 4));
+ if (type.SequenceEqual("VP8 "u8)) sawImage = true;
+ else if (sawImage && (type.SequenceEqual("ALPH"u8) || type.SequenceEqual("VP8X"u8))) return true;
+ var next = offset + 8L + length + (length & 1);
+ if (next > file.Length) break;
+ offset = (int)next;
+ }
+ return false;
+ }
+
+ private static int FindChunk(byte[] file, ReadOnlySpan type)
+ {
+ for (var offset = 12; offset + 8 <= file.Length;)
+ {
+ if (file.AsSpan(offset, 4).SequenceEqual(type)) return offset;
+ var length = BinaryPrimitives.ReadInt32LittleEndian(file.AsSpan(offset + 4));
+ offset += 8 + length + (length & 1);
+ }
+ throw new InvalidOperationException("No such chunk.");
+ }
+
+ // The file with the last drop bytes of its VP8 chunk removed and the chunk / RIFF sizes fixed.
+ private static byte[] Shorten(byte[] file, int vp8, int length, int drop)
+ {
+ var end = vp8 + 8 + length;
+ var newLength = length - drop;
+ var head = file.AsSpan(0, vp8 + 8 + newLength).ToArray();
+ var pad = new byte[newLength & 1];
+ var tail = file.AsSpan(end + (length & 1)).ToArray();
+ var result = head.Concat(pad).Concat(tail).ToArray();
+ BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(vp8 + 4), newLength);
+ BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan(4), result.Length - 8);
+ return result;
+ }
+}