From 4f14399acd80359e034d3369ab226baf7ed356b0 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:41:12 +0800 Subject: [PATCH 1/2] Jpeg: streaming decode from a forward-only stream JpegImageDecoder implements IStreamingImageDecoder (Registration.CreateRowReader), plus OpenRowReader / OpenRowReaderAsync over a Stream. A sequential frame whose first scan interleaves every component is decoded as it arrives, MCU row by MCU row, with the existing two-MCU-row strips; rows go to the caller's band and the rest stay pending in the strips. Each MCU row (and each marker step after the scan) is a unit: the entropy state is checkpointed before it and rolled back when it read past the buffered input and the stream has not ended, so the rows equal TryDecodeInto's byte for byte. DCT-domain scales 2/4/8 stream too; progressive, multi-scan, region, orientation and larger scales take the buffered fallback. The span decode keeps its arithmetic and sequence: reads past the data now also set an overrun flag, EmitRows stops at a row limit (OutY for a whole decode), and the streaming scan's per-MCU-row body is factored out. Co-Authored-By: Claude Opus 5.5 --- .../AbBenchmarks.cs | 48 +- .../JpegCore.Streaming.cs | 464 ++++++++++++++++++ src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs | 235 +++++---- src/Sdcb.SimdCodecs.Jpeg/JpegImageDecoder.cs | 48 +- src/Sdcb.SimdCodecs.Jpeg/JpegRowReader.cs | 259 ++++++++++ .../PublicAPI.Unshipped.txt | 3 + src/Sdcb.SimdCodecs.Jpeg/README.md | 14 + .../JpegDecoderOracleTests.cs | 2 +- tests/Sdcb.SimdCodecs.Tests/JpegFuzzTests.cs | 86 ++++ .../JpegStreamingDecodeTests.cs | 374 ++++++++++++++ 10 files changed, 1438 insertions(+), 95 deletions(-) create mode 100644 src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs create mode 100644 src/Sdcb.SimdCodecs.Jpeg/JpegRowReader.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/JpegStreamingDecodeTests.cs diff --git a/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/AbBenchmarks.cs b/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/AbBenchmarks.cs index 4df8499..aae6192 100644 --- a/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/AbBenchmarks.cs +++ b/benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/AbBenchmarks.cs @@ -2,6 +2,7 @@ using System.Text; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Reports; +using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Jpeg; namespace Sdcb.SimdCodecs.Jpeg.Benchmarks; @@ -59,6 +60,13 @@ public void Setup() _rgba = new byte[info.Width * info.Height * 4]; _turbo = new TurboDecoder(fast: false); BaselineDecoder.DecodeTo(_jpeg, _rgba); + + // A benchmark refuses to time wrong output: the streaming reader's rows must be the span decode's. + var expected = new byte[_rgba.Length]; + JpegDecoder.DecodeTo(_jpeg, expected); + Streaming(); + if (!_rgba.AsSpan().SequenceEqual(expected)) + throw new InvalidOperationException($"{Case}: the streaming reader's rows differ from JpegDecoder.DecodeTo."); } [GlobalCleanup] @@ -70,6 +78,24 @@ public void Setup() [Benchmark] public (int, int) Current() => JpegDecoder.DecodeTo(_jpeg, _rgba); + /// + /// The streaming reader () over the same bytes as a stream, every row read + /// into the same buffer, 64 KB of input at a time: what a forward-only decode costs over the span decode + /// (). Progressive files take its buffered fallback. + /// + [Benchmark] + public (int, int) Streaming() + { + using var reader = JpegImageDecoder.OpenRowReader(new MemoryStream(_jpeg, writable: false), PixelFormat.Rgba32); + reader.Initialize(); + while (reader.RowsRead < reader.Height) + reader.ReadRows(_rgba.AsSpan(reader.RowsRead * reader.Width * 4), StreamBand); + return (reader.Width, reader.Height); + } + + /// Rows per read: a typical consumer band. + private const int StreamBand = 16; + [Benchmark] public (int, int) LibjpegTurbo() => _turbo!.DecodeRgba(_jpeg, _rgba); @@ -93,7 +119,7 @@ public void Setup() public (int, int) EntropyCore() => JpegDiagnostics.DecodeTo(_jpeg, _rgba, JpegAblation.SkipIdct | JpegAblation.SkipUpsample | JpegAblation.SkipColor | JpegAblation.SkipBlockSink); - public static readonly string[] CoreMethods = [nameof(Baseline), nameof(Current), nameof(LibjpegTurbo)]; + public static readonly string[] CoreMethods = [nameof(Baseline), nameof(Current), nameof(Streaming), nameof(LibjpegTurbo)]; public static readonly string[] AblationMethods = [nameof(NoIdct), nameof(NoUpsample), nameof(NoColor), nameof(EntropyOnly), nameof(EntropyCore), nameof(LibjpegTurboPlanes)]; /// Per-file medians → markdown: speed vs baseline and turbo, and stage costs by ablation. @@ -115,14 +141,15 @@ public static string Render(Summary summary, string baselineLabel) var sb = new StringBuilder(); sb.AppendLine($"Baseline: {baselineLabel}. Times are BenchmarkDotNet medians in ms."); sb.AppendLine(); - sb.Append("| File | turbo | baseline | current | current ÷ baseline | current ÷ turbo |"); + sb.Append("| File | turbo | baseline | current | streaming | current ÷ baseline | current ÷ turbo | streaming ÷ current |"); if (ablated) sb.Append(" IDCT | upsample | colour | entropy + rest | entropy | rest | turbo planes | turbo up+colour |"); sb.AppendLine(); - sb.Append("|---|---:|---:|---:|---:|---:|"); + sb.Append("|---|---:|---:|---:|---:|---:|---:|---:|"); if (ablated) sb.Append("---:|---:|---:|---:|---:|---:|---:|---:|"); sb.AppendLine(); - double logBase = 0, logTurbo = 0; + double logBase = 0, logTurbo = 0, logStream = 0; + var streamed = 0; var n = 0; foreach (var c in cases) { @@ -133,7 +160,15 @@ public static string Render(Summary summary, string baselineLabel) n++; logBase += Math.Log(current.Value / baseline.Value); logTurbo += Math.Log(current.Value / turbo.Value); - sb.Append($"| `{c}` | {Ms(turbo.Value)} | {Ms(baseline.Value)} | {Ms(current.Value)} | {X(current.Value / baseline.Value)} | {X(current.Value / turbo.Value)} |"); + var streaming = Get(c, nameof(Streaming)); + if (streaming is { } st) + { + streamed++; + logStream += Math.Log(st / current.Value); + } + + sb.Append($"| `{c}` | {Ms(turbo.Value)} | {Ms(baseline.Value)} | {Ms(current.Value)} | {(streaming is { } s1 ? Ms(s1) : "—")} | " + + $"{X(current.Value / baseline.Value)} | {X(current.Value / turbo.Value)} | {(streaming is { } s2 ? X(s2 / current.Value) : "—")} |"); if (ablated) { string Cost(string m) => Get(c, m) is { } v ? Ms(current.Value - v) : "—"; @@ -149,7 +184,8 @@ public static string Render(Summary summary, string baselineLabel) } if (n > 0) - sb.AppendLine($"| **geomean** | | | | **{X(Math.Exp(logBase / n))}** | **{X(Math.Exp(logTurbo / n))}** |{(ablated ? " | | | | | | | |" : "")}"); + sb.AppendLine($"| **geomean** | | | | | **{X(Math.Exp(logBase / n))}** | **{X(Math.Exp(logTurbo / n))}** | " + + $"{(streamed > 0 ? $"**{X(Math.Exp(logStream / streamed))}**" : "")} |{(ablated ? " | | | | | | | |" : "")}"); if (ablated) { sb.AppendLine(); diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs new file mode 100644 index 0000000..fa196ab --- /dev/null +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs @@ -0,0 +1,464 @@ +using System.Buffers; +using Sdcb.SimdCodecs.Abstractions; + +namespace Sdcb.SimdCodecs.Jpeg; + +/// +/// Streaming decode (): the same engine run over the input buffered so far, a call at a time. +/// +/// Between calls the engine's state lives in a ; each call rebuilds the engine over the new +/// window of input () and suspends it again. The unit of work is the +/// MCU row of the frame's one streaming scan, then the markers after it: before each, the entropy state is checkpointed, +/// and when the unit read past the end of the window () and the stream has not ended, it is rolled +/// back and the call asks for more input. Only whole units are consumed, so the output is the whole decode's bit for bit: +/// a unit either sees every byte it reads exactly as a decode of the complete file does, or it is undone. Once the stream +/// has ended, reads past the end are the zeros a decode of the complete (short) file reads. +/// +/// +/// Rows go to the caller's band ( from output row , at most up to +/// ). Rows the strips could give past the band stay pending there; the next MCU row is decoded +/// only once nothing more can be emitted without it, which is exactly when a whole decode decodes it, so the strips hold +/// what they would. The last row is held back until the markers after the scan have been read, so a stream the whole +/// decode rejects there fails before its last row is handed out. +/// +/// +internal ref partial struct JpegCore +{ + private const int TailRows = 0; // MCU rows of the streaming scan still to decode + private const int TailAfterScan = 1; // the scan's data is over: skip junk, read the next marker + private const int TailMarker = 2; // _sTailMarker is the next marker to handle + private const int TailDone = 3; // EOI, or a marker that ends the image + + /// True when a read went past the end of the data since the last checkpoint. + internal readonly bool Overrun => _overrun; + + /// The read position in the data. + internal readonly int Position => _pos; + + /// + /// Parses the header up to the first scan's header: SOI → SOF (, as + /// reads it), then the markers before the first SOS, then that SOS. True when the frame streams: sequential, and its + /// first scan interleaves every component. False for anything a whole decode handles otherwise (progressive, + /// non-interleaved, or a frame with no scan at all); the position is then meaningless. + /// + internal bool StreamHeader(out JpegInfo info) + { + _restartInterval = 0; + DecodeHeader(ScanMode.Load); + info = FrameInfo(); + OutX = (ImgX + _scale - 1) / _scale; + OutY = (ImgY + _scale - 1) / _scale; + if (_progressive) + return false; + + // A whole decode picks the colour transform (PrepareOutput) from the markers before SOF, before it reads the ones + // after it: a JFIF or Adobe segment between SOF and SOS must not change it here either. + var (jfif, app14) = (_jfif, _app14ColorTransform); + + // The markers between SOF and the first scan, as DecodeScans reads them. + int m = GetMarker(); + while (m != 0xda) + { + if (m == 0xd9) + return false; // no scan: zero samples + if (m == 0xdc) + { + ReadDnl(); + } + else if (!ProcessMarker(m)) + { + return false; // salvaged as zero samples + } + + m = GetMarker(); + } + + ProcessScanHeader(); + (_jfif, _app14ColorTransform) = (jfif, app14); + return _scanN == ImgN; + } + + /// After a true : sets up the output and the scan's entropy state. + internal void BeginStreaming(JpegPixelFormat format) + { + _format = format; + _outRow = 0; + _outBpp = BytesPerPixel(format); + (_winX0, _winY0, _winW, _winY1) = (0, 0, OutX, OutY); + _destY0 = 0; + _emitLimit = 0; + _mode = DecodeMode.Streaming; + _streamDone = true; // a later scan sending a component again is decoded and dropped, as in DecodeScans + PrepareFormat(format); + Reset(); + _sNextMcu = 0; + _sZeroFill = false; + _sTail = TailRows; + _sMinInput = 0; + } + + /// + /// Writes up to rows (never past the image) into , row + /// i at i × , decoding what they need from the data. Done when it wrote + /// them all; NeedMoreData when the data ran out first ( is then at the start of the unit to + /// retry). Not called after the last row. + /// + internal OperationStatus StreamRows(bool isFinal, Span dest, int stride, int rowCount, out int rowsWritten) + { + _dest = dest; + _stride = stride; + _destY0 = _outRow; + var start = _outRow; + var status = StreamUntil(Math.Min(OutY, _outRow + rowCount), isFinal); + rowsWritten = _outRow - start; + _dest = default; + return status; + } + + private OperationStatus StreamUntil(int target, bool isFinal) + { + Span data = stackalloc short[64]; + Span blockComp = stackalloc int[MaxBlocksPerMcu]; + Span blockDx = stackalloc int[MaxBlocksPerMcu]; + Span blockDy = stackalloc int[MaxBlocksPerMcu]; + // The scan's MCU layout; the markers after the scan may change the scan fields, but only once its rows are in. + var blocks = _sNextMcu < _imgMcuY ? BlockOrder(blockComp, blockDx, blockDy) : 0; + while (true) + { + _emitLimit = _sTail == TailDone ? target : Math.Min(target, OutY - 1); + EmitRows(); + if (_outRow >= target) + return OperationStatus.Done; + + if (_sNextMcu < _imgMcuY) + { + var m = _sNextMcu; + if (_sZeroFill) + { + // ZeroFillFrom, one MCU row at a time. + for (var k = 0; k < ImgN; ++k) + { + var c = _comp[k]; + c.Ring.AsSpan(RingOffset(c, m * c.RowsPerMcu), c.RowsPerMcu * c.W2).Clear(); + } + } + else + { + if (!isFinal && _data.Length - _pos < _sMinInput) + return OperationStatus.NeedMoreData; + var cp = Checkpoint(); + bool ended; + try + { + ended = DecodeStreamingRow(m, data, blockComp.Slice(0, blocks), blockDx.Slice(0, blocks), blockDy.Slice(0, blocks)); + } + catch (InvalidDataException) when (_overrun && !isFinal) + { + Rollback(cp); + return OperationStatus.NeedMoreData; + } + + if (_overrun && !isFinal) + { + Rollback(cp); + return OperationStatus.NeedMoreData; + } + + _sMinInput = 0; + _sZeroFill = ended; + } + + _sNextMcu = m + 1; + CommitMcuRow(m); + continue; + } + + if (_sTail == TailRows) + _sTail = TailAfterScan; + if (_sTail == TailDone) + throw new InvalidOperationException("JPEG: the streaming decode ran out of rows."); // unreachable + if (TailStep(isFinal) == OperationStatus.NeedMoreData) + return OperationStatus.NeedMoreData; + } + } + + /// One marker step after the streaming scan, as takes it. + private OperationStatus TailStep(bool isFinal) + { + if (!isFinal && _data.Length - _pos < _sMinInput) + return OperationStatus.NeedMoreData; + var cp = Checkpoint(); + try + { + if (_sTail == TailAfterScan) + { + if (_marker == 0xff) + _marker = SkipJunkAtEnd(); + int m = GetMarker(); + if (m >= 0xd0 && m <= 0xd7) // stray RSTn between scans + m = GetMarker(); + _sTailMarker = m; + _sTail = TailMarker; + } + else + { + var m = _sTailMarker; + if (m == 0xd9) + { + _sTail = TailDone; + } + else if (!isFinal && HasLengthField(m) && !SegmentBuffered()) + { + // A table segment is applied only whole: one cut short would write the zeros past the window into + // whichever table they name, and a retry would not undo that. + _sMinInput = _data.Length - _pos < 2 ? 2 : Math.Max(2, (_data[_pos] << 8) | _data[_pos + 1]); + return OperationStatus.NeedMoreData; + } + else if (m == 0xda) + { + // A scan after the streaming one sends a component again (invalid): decoded and dropped. + ProcessScanHeader(); + Reset(); + DecodeBaselineScan(discard: true); + _sTail = TailAfterScan; + } + else if (m == 0xdc) + { + ReadDnl(); + _sTailMarker = GetMarker(); + } + else if (!ProcessMarker(m)) + { + _sTail = TailDone; // salvage what was decoded + } + else + { + _sTailMarker = GetMarker(); + } + } + } + catch (InvalidDataException) when (_overrun && !isFinal) + { + Rollback(cp); + return OperationStatus.NeedMoreData; + } + + if (_overrun && !isFinal) + { + Rollback(cp); + return OperationStatus.NeedMoreData; + } + + _sMinInput = 0; + return OperationStatus.Done; + } + + private void ReadDnl() + { + var ld = Get16(); + var nl = Get16(); + if (ld != 4) + throw Err("bad DNL len"); + if (nl != ImgY) + throw Err("bad DNL height"); + } + + /// Markers whose segment or reads by its length. + private static bool HasLengthField(int m) => m is 0xda or 0xdb or 0xc4 or 0xdd or 0xfe or (>= 0xe0 and <= 0xef); + + /// True when the segment at the read position (its 16-bit length first) is in the data whole. + private readonly bool SegmentBuffered() + { + var left = _data.Length - _pos; + return left >= 2 && left >= ((_data[_pos] << 8) | _data[_pos + 1]); + } + + private static int BytesPerPixel(JpegPixelFormat format) => format switch + { + JpegPixelFormat.Rgba32 or JpegPixelFormat.Bgra32 => 4, + JpegPixelFormat.Rgb24 or JpegPixelFormat.Bgr24 => 3, + _ => 1, + }; + + // ------------------------------------------------------------ checkpoints + + /// Everything a unit of the streaming decode changes, besides strip samples it rewrites on a retry. + private struct Mark + { + public int Pos, BitCnt, Todo, EobRun, RestartInterval, Dc0, Dc1, Dc2, Dc3, Tail, TailMarker; + public ulong BitBuf; + public byte Marker; + public bool NoMore; + } + + private Mark Checkpoint() + { + _overrun = false; + return new Mark + { + Pos = _pos, BitCnt = _bitCnt, BitBuf = _bitBuf, Todo = _todo, EobRun = _eobRun, RestartInterval = _restartInterval, + Dc0 = _comp[0].DcPred, Dc1 = _comp[1].DcPred, Dc2 = _comp[2].DcPred, Dc3 = _comp[3].DcPred, + Tail = _sTail, TailMarker = _sTailMarker, Marker = _marker, NoMore = _nomore, + }; + } + + /// Undoes the unit since , and waits for a quarter more input before retrying it, so a + /// stream arriving a byte at a time costs a bounded number of attempts per unit rather than one per byte. + private void Rollback(in Mark cp) + { + (_pos, _bitCnt, _bitBuf, _todo, _eobRun, _restartInterval) = (cp.Pos, cp.BitCnt, cp.BitBuf, cp.Todo, cp.EobRun, cp.RestartInterval); + (_comp[0].DcPred, _comp[1].DcPred, _comp[2].DcPred, _comp[3].DcPred) = (cp.Dc0, cp.Dc1, cp.Dc2, cp.Dc3); + (_sTail, _sTailMarker, _marker, _nomore) = (cp.Tail, cp.TailMarker, cp.Marker, cp.NoMore); + _overrun = false; + var avail = (long)_data.Length - _pos; + _sMinInput = (int)Math.Min(Array.MaxLength, avail + avail / 4 + 1); + } + + // ------------------------------------------------------------ suspension + + /// + /// The engine's state between two streaming calls: every field but the spans (, + /// , ), which a call supplies. JpegStreamingDecodeTests checks by + /// reflection that every other field of has its namesake here. + /// + internal sealed class Suspended + { + internal int _pos; + internal JpegColorTransform ColorTransform; + internal byte _marker; + internal bool _nomore; + internal int ImgX, ImgY, ImgN; + internal int _imgHMax, _imgVMax; + internal int _imgMcuX, _imgMcuY, _imgMcuW, _imgMcuH; + internal bool _progressive, _jfif; + internal int _app14ColorTransform; + internal ImageOrientation _orientation; + internal bool _exifSeen; + internal int _rgbCount, _restartInterval, _todo, _eobRun; + internal int _scanN, _specStart, _specEnd, _succHigh, _succLow; + internal DecoderState? _state; + internal int _scale; + internal int OutX, OutY; + internal JpegBlockHook? BlockHook; + internal JpegAblation Ablation; + internal CancellationToken CancellationToken; + internal DecodeMode _mode; + internal bool _streamDone; + internal int _stride; + internal JpegPixelFormat _format; + internal byte[]? _packScratch; + internal bool _lumaOnly; + internal int _outRow, _outBpp; + internal bool _hasWindow; + internal int _winX0, _winY0, _winW, _winY1, _destY0, _emitLimit; + internal bool _overrun; + internal byte[]? _winScratch; + internal bool _isRgb, _chroma16; + internal int _fourTransform; + internal bool CapturePlanes; + internal ulong _bitBuf; + internal JpegHuffman? _acSlowTable; + internal int _bitCnt; + internal int _sNextMcu; + internal bool _sZeroFill; + internal int _sTail, _sTailMarker, _sMinInput; + } + + /// The engine suspended in , over : the input from the position it + /// was suspended at. + internal JpegCore(ReadOnlySpan data, Suspended s) + { + _data = data; + _state = s._state!; + _order = _state.Order; + _huffDc = _state.HuffDc; + _huffAc = _state.HuffAc; + _dequant = _state.Dequant; + _comp = _state.Comp; + _scale = s._scale; + _blockSize = 8 / _scale; + + _pos = s._pos; + ColorTransform = s.ColorTransform; + _marker = s._marker; + _nomore = s._nomore; + (ImgX, ImgY, ImgN) = (s.ImgX, s.ImgY, s.ImgN); + (_imgHMax, _imgVMax) = (s._imgHMax, s._imgVMax); + (_imgMcuX, _imgMcuY, _imgMcuW, _imgMcuH) = (s._imgMcuX, s._imgMcuY, s._imgMcuW, s._imgMcuH); + (_progressive, _jfif) = (s._progressive, s._jfif); + _app14ColorTransform = s._app14ColorTransform; + _orientation = s._orientation; + _exifSeen = s._exifSeen; + (_rgbCount, _restartInterval, _todo, _eobRun) = (s._rgbCount, s._restartInterval, s._todo, s._eobRun); + (_scanN, _specStart, _specEnd, _succHigh, _succLow) = (s._scanN, s._specStart, s._specEnd, s._succHigh, s._succLow); + (OutX, OutY) = (s.OutX, s.OutY); + BlockHook = s.BlockHook; + Ablation = s.Ablation; + CancellationToken = s.CancellationToken; + _mode = s._mode; + _streamDone = s._streamDone; + _stride = s._stride; + _format = s._format; + _packScratch = s._packScratch; + _lumaOnly = s._lumaOnly; + (_outRow, _outBpp) = (s._outRow, s._outBpp); + _hasWindow = s._hasWindow; + (_winX0, _winY0, _winW, _winY1, _destY0, _emitLimit) = (s._winX0, s._winY0, s._winW, s._winY1, s._destY0, s._emitLimit); + _overrun = s._overrun; + _winScratch = s._winScratch; + (_isRgb, _chroma16) = (s._isRgb, s._chroma16); + _fourTransform = s._fourTransform; + CapturePlanes = s.CapturePlanes; + _bitBuf = s._bitBuf; + _acSlowTable = s._acSlowTable; + _bitCnt = s._bitCnt; + _sNextMcu = s._sNextMcu; + _sZeroFill = s._sZeroFill; + (_sTail, _sTailMarker, _sMinInput) = (s._sTail, s._sTailMarker, s._sMinInput); + } + + /// Saves the engine into , its position made relative to + /// (where the next call's data starts). + internal readonly void Suspend(Suspended s, int consumed) + { + s._pos = _pos - consumed; + s.ColorTransform = ColorTransform; + s._marker = _marker; + s._nomore = _nomore; + (s.ImgX, s.ImgY, s.ImgN) = (ImgX, ImgY, ImgN); + (s._imgHMax, s._imgVMax) = (_imgHMax, _imgVMax); + (s._imgMcuX, s._imgMcuY, s._imgMcuW, s._imgMcuH) = (_imgMcuX, _imgMcuY, _imgMcuW, _imgMcuH); + (s._progressive, s._jfif) = (_progressive, _jfif); + s._app14ColorTransform = _app14ColorTransform; + s._orientation = _orientation; + s._exifSeen = _exifSeen; + (s._rgbCount, s._restartInterval, s._todo, s._eobRun) = (_rgbCount, _restartInterval, _todo, _eobRun); + (s._scanN, s._specStart, s._specEnd, s._succHigh, s._succLow) = (_scanN, _specStart, _specEnd, _succHigh, _succLow); + s._state = _state; + s._scale = _scale; + (s.OutX, s.OutY) = (OutX, OutY); + s.BlockHook = BlockHook; + s.Ablation = Ablation; + s.CancellationToken = CancellationToken; + s._mode = _mode; + s._streamDone = _streamDone; + s._stride = _stride; + s._format = _format; + s._packScratch = _packScratch; + s._lumaOnly = _lumaOnly; + (s._outRow, s._outBpp) = (_outRow, _outBpp); + s._hasWindow = _hasWindow; + (s._winX0, s._winY0, s._winW, s._winY1, s._destY0, s._emitLimit) = (_winX0, _winY0, _winW, _winY1, _destY0, _emitLimit); + s._overrun = _overrun; + s._winScratch = _winScratch; + (s._isRgb, s._chroma16) = (_isRgb, _chroma16); + s._fourTransform = _fourTransform; + s.CapturePlanes = CapturePlanes; + s._bitBuf = _bitBuf; + s._acSlowTable = _acSlowTable; + s._bitCnt = _bitCnt; + s._sNextMcu = _sNextMcu; + s._sZeroFill = _sZeroFill; + (s._sTail, s._sTailMarker, s._sMinInput) = (_sTail, _sTailMarker, _sMinInput); + } +} diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs index 5476be6..33374ef 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs @@ -47,7 +47,7 @@ namespace Sdcb.SimdCodecs.Jpeg; /// samples; the later scan is entropy-decoded and dropped. /// /// -internal ref struct JpegCore +internal ref partial struct JpegCore { // Not readonly: an abbreviated table-specification stream (Tables) is parsed through the same reader first. private ReadOnlySpan _data; @@ -133,7 +133,7 @@ public JpegCore(ReadOnlySpan data, int scale) /// objects, so nothing — a table, a predictor, a pooled-buffer reference — can leak /// from one image into the next. /// - private sealed class DecoderState + internal sealed class DecoderState { public readonly int[] Order = new int[4]; public readonly JpegHuffman[] HuffDc = { new(), new(), new(), new() }; @@ -165,7 +165,7 @@ public static DecoderState Rent() public static void Return(DecoderState s) => t_cached = s; } - private sealed class Component + internal sealed class Component { public int Id, H, V, Tq, Hd, Ha; public JpegHuffman? DcTable, AcTable; // the current scan's tables @@ -232,7 +232,7 @@ private enum ScanMode /// over several scans, keep every block's coefficients and run IDCT + output /// MCU row by MCU row once the scans are in. /// - private enum DecodeMode + internal enum DecodeMode { Undecided, Streaming, @@ -253,6 +253,16 @@ private enum DecodeMode // computed exactly as in a whole-image decode, so the window's pixels are the whole decode's. private bool _hasWindow; private int _winX0, _winY0, _winW, _winY1; + private int _destY0; // the output row at the start of _dest + private int _emitLimit; // EmitRows writes rows below this one (OutY, or the end of a streaming band) + private bool _overrun; // a read went past the end of _data (see Get8) + + // Streaming decode progress (JpegCore.Streaming.cs; all instance fields stay in this declaration). + private int _sNextMcu; // the next MCU row to decode + private bool _sZeroFill; // the scan ended early: the MCU rows left are zero samples + private int _sTail; // TailRows … TailDone + private int _sTailMarker; + private int _sMinInput; // after a unit was undone: the input it waits for before trying again private byte[]? _winScratch; // one full output row, when the window drops columns private bool _isRgb; private bool _chroma16; @@ -285,7 +295,12 @@ private static void RawFourRow(Span outRow, ReadOnlySpan c0, ReadOnl public JpegInfo ParseInfo() { DecodeHeader(ScanMode.Header); + return FrameInfo(); + } + /// The of the frame header just read (what returns). + private readonly JpegInfo FrameInfo() + { // Header-scan mode returns before the frame header computes the sampling // maxima, so derive subsampling directly from the component factors here. var hMax = 1; @@ -360,26 +375,16 @@ public void DecodeInto(Span dest, int stride, JpegPixelFormat format = Jpe _stride = stride; _format = format; _outRow = 0; - _outBpp = format switch - { - JpegPixelFormat.Rgba32 or JpegPixelFormat.Bgra32 => 4, - JpegPixelFormat.Rgb24 or JpegPixelFormat.Bgr24 => 3, - _ => 1, - }; + _outBpp = BytesPerPixel(format); if (!_hasWindow) (_winX0, _winY0, _winW, _winY1) = (0, 0, OutX, OutY); if (_winX0 != 0 || _winW != OutX) _winScratch = ArrayPool.Shared.Rent(OutX * _outBpp); + _destY0 = _winY0; + _emitLimit = OutY; _mode = _progressive ? DecodeMode.Coefficients : DecodeMode.Undecided; _streamDone = false; - PrepareOutput(); - // Grey from a YCbCr frame is its Y plane (see JpegPixelFormat.Gray8): the chroma blocks are still - // entropy-decoded, as the scans interleave them, but never inverse-transformed, upsampled or - // colour-converted. RGB-coded, CMYK and YCCK frames have no luma plane; their grey is the luma - // of the RGB row. - _lumaOnly = format == JpegPixelFormat.Gray8 && ImgN == 3 && !_isRgb; - if (format is JpegPixelFormat.Rgb24 or JpegPixelFormat.Bgr24 || (format == JpegPixelFormat.Gray8 && ImgN != 1 && !_lumaOnly)) - _packScratch = ArrayPool.Shared.Rent(OutX * 4); + PrepareFormat(format); var reachedEoi = DecodeScans(); @@ -396,6 +401,19 @@ public void DecodeInto(Span dest, int stride, JpegPixelFormat format = Jpe } } + /// The output set-up both a whole decode and a streaming one make once the frame header is read. + private void PrepareFormat(JpegPixelFormat format) + { + PrepareOutput(); + // Grey from a YCbCr frame is its Y plane (see JpegPixelFormat.Gray8): the chroma blocks are still + // entropy-decoded, as the scans interleave them, but never inverse-transformed, upsampled or + // colour-converted. RGB-coded, CMYK and YCCK frames have no luma plane; their grey is the luma + // of the RGB row. + _lumaOnly = format == JpegPixelFormat.Gray8 && ImgN == 3 && !_isRgb; + if (format is JpegPixelFormat.Rgb24 or JpegPixelFormat.Bgr24 || (format == JpegPixelFormat.Gray8 && ImgN != 1 && !_lumaOnly)) + _packScratch = ArrayPool.Shared.Rent(OutX * 4); + } + /// /// After with set: copies /// each component's decoded sample plane (post-IDCT, pre-upsampling, at the @@ -523,7 +541,9 @@ private void ZeroBlock(Component c, int bx, int by) private void EmitRows() { - while (_outRow < OutY) + // _emitLimit is OutY for a whole decode; a streaming decode stops at the end of the caller's band, leaving the + // rows the strips can still give pending until the next call. + while (_outRow < _emitLimit) { for (var k = 0; k < ImgN; ++k) { @@ -644,13 +664,13 @@ private void EmitRow(int j) /// Where output row (inside the window) is written: its destination row, or the /// full-row scratch when the window drops columns. private readonly Span TargetRow(int j) => - _winScratch != null ? _winScratch.AsSpan(0, OutX * _outBpp) : _dest.Slice((j - _winY0) * _stride, OutX * _outBpp); + _winScratch != null ? _winScratch.AsSpan(0, OutX * _outBpp) : _dest.Slice((j - _destY0) * _stride, OutX * _outBpp); /// Copies the window's columns of row from the scratch row to the destination. private readonly void FlushRow(int j) { if (_winScratch != null) - _winScratch.AsSpan(_winX0 * _outBpp, _winW * _outBpp).CopyTo(_dest.Slice((j - _winY0) * _stride, _winW * _outBpp)); + _winScratch.AsSpan(_winX0 * _outBpp, _winW * _outBpp).CopyTo(_dest.Slice((j - _destY0) * _stride, _winW * _outBpp)); } /// Writes the RGBA (or BGRA) row as the 3- or 1-byte output format. @@ -748,9 +768,25 @@ private void ReturnPools() // ============================== byte reader ============================== - private bool AtEof => _pos >= _data.Length; + // Every read past the end of _data reads 0 (as stb does past end of file) and sets _overrun: a streaming decode, + // whose _data is only the input buffered so far, then knows the result depends on bytes not yet there. - private byte Get8() => _pos < _data.Length ? _data[_pos++] : (byte)0; + /// True at the end of the data (and so, for a streaming decode, possibly short of it). + private bool AtEnd() + { + if (_pos < _data.Length) + return false; + _overrun = true; + return true; + } + + private byte Get8() + { + if (_pos < _data.Length) + return _data[_pos++]; + _overrun = true; + return 0; + } private int Get16() { @@ -758,7 +794,18 @@ private int Get16() return (hi << 8) | Get8(); } - private void Skip(int n) => _pos = Math.Min(_data.Length, _pos + n); + private void Skip(int n) + { + if (n > _data.Length - _pos) + { + _overrun = true; + _pos = _data.Length; + } + else + { + _pos += n; + } + } // ============================== bit reader ============================== // @@ -1631,79 +1678,93 @@ private void ParseEntropyCodedData() private void DecodeStreamingScan() { Span data = stackalloc short[64]; - if (_scanN == 1) + Span blockComp = stackalloc int[MaxBlocksPerMcu]; + Span blockDx = stackalloc int[MaxBlocksPerMcu]; + Span blockDy = stackalloc int[MaxBlocksPerMcu]; + var blocks = BlockOrder(blockComp, blockDx, blockDy); + for (var m = 0; m < _imgMcuY; ++m) { - // Single-component frame: its own block grid, no MCU padding; an "MCU - // row" here is the V block rows one strip half holds. - var n = _order[0]; - var c = _comp[n]; - var w = (c.X + 7) >> 3; - var h = (c.Y + 7) >> 3; - for (var m = 0; m < _imgMcuY; ++m) + if (DecodeStreamingRow(m, data, blockComp.Slice(0, blocks), blockDx.Slice(0, blocks), blockDy.Slice(0, blocks))) { - var by0 = m * c.V; - var by1 = Math.Min(h, by0 + c.V); - for (var by = by1; by < by0 + c.V; ++by) - ZeroBlockRow(c, by); - var end = DecodeSingleRows(m, n, by0, by1, w, data); - if (end >= 0) - { - var (eby, ebx) = Math.DivRem(end, w); - for (var x = ebx + 1; x < w; ++x) - ZeroBlock(c, x, eby); - for (var y = eby + 1; y < by1; ++y) - ZeroBlockRow(c, y); - CommitMcuRow(m); - ZeroFillFrom(m + 1); - return; - } - + // The scan ended early: the rest of the frame is zero samples. CommitMcuRow(m); + ZeroFillFrom(m + 1); + return; } + + CommitMcuRow(m); } - else + } + + /// + /// The blocks of one interleaved MCU of the current scan, in scan order: block b belongs to component + /// [b] at ([b], [b]) in its H×V grid. + /// Returns the block count (≤ ). + /// + private readonly int BlockOrder(Span blockComp, Span blockDx, Span blockDy) + { + var blocks = 0; + for (var k = 0; k < _scanN; ++k) { - // Interleaved: full MCU sweep, h×v blocks per component per MCU, in scan order. - Span blockComp = stackalloc int[MaxBlocksPerMcu]; - Span blockDx = stackalloc int[MaxBlocksPerMcu]; - Span blockDy = stackalloc int[MaxBlocksPerMcu]; - var blocks = 0; - for (var k = 0; k < _scanN; ++k) + var c = _comp[_order[k]]; + for (var y = 0; y < c.V; ++y) { - var c = _comp[_order[k]]; - for (var y = 0; y < c.V; ++y) + for (var x = 0; x < c.H; ++x) { - for (var x = 0; x < c.H; ++x) - { - blockComp[blocks] = _order[k]; - blockDx[blocks] = x; - blockDy[blocks++] = y; - } + blockComp[blocks] = _order[k]; + blockDx[blocks] = x; + blockDy[blocks++] = y; } } + } - for (var m = 0; m < _imgMcuY; ++m) - { - var i = DecodeInterleavedRow(m, data, blockComp.Slice(0, blocks), blockDx.Slice(0, blocks), blockDy.Slice(0, blocks)); - if (i >= 0) - { - // The scan ended early: the rest of the frame is zero samples. - for (var k = 0; k < ImgN; ++k) - { - var c = _comp[k]; - for (var by = m * c.V; by < (m + 1) * c.V; ++by) - for (var bx = (i + 1) * c.H; bx < _imgMcuX * c.H; ++bx) - ZeroBlock(c, bx, by); - } + return blocks; + } - CommitMcuRow(m); - ZeroFillFrom(m + 1); - return; - } + /// + /// Entropy-decodes and inverse-transforms MCU row of the streaming scan into its strip half, + /// without committing it. Returns true when the scan ended inside the row: the rest of the row is zero samples, and so + /// is every later row. + /// + private bool DecodeStreamingRow(int m, scoped Span data, scoped ReadOnlySpan blockComp, + scoped ReadOnlySpan blockDx, scoped ReadOnlySpan blockDy) + { + if (_scanN == 1) + { + // Single-component frame: its own block grid, no MCU padding; an "MCU + // row" here is the V block rows one strip half holds. + var n = _order[0]; + var c = _comp[n]; + var w = (c.X + 7) >> 3; + var h = (c.Y + 7) >> 3; + var by0 = m * c.V; + var by1 = Math.Min(h, by0 + c.V); + for (var by = by1; by < by0 + c.V; ++by) + ZeroBlockRow(c, by); + var end = DecodeSingleRows(m, n, by0, by1, w, data); + if (end < 0) + return false; + var (eby, ebx) = Math.DivRem(end, w); + for (var x = ebx + 1; x < w; ++x) + ZeroBlock(c, x, eby); + for (var y = eby + 1; y < by1; ++y) + ZeroBlockRow(c, y); + return true; + } - CommitMcuRow(m); - } + // Interleaved: full MCU sweep, h×v blocks per component per MCU, in scan order. + var i = DecodeInterleavedRow(m, data, blockComp, blockDx, blockDy); + if (i < 0) + return false; + for (var k = 0; k < ImgN; ++k) + { + var c = _comp[k]; + for (var by = m * c.V; by < (m + 1) * c.V; ++by) + for (var bx = (i + 1) * c.H; bx < _imgMcuX * c.H; ++bx) + ZeroBlock(c, bx, by); } + + return true; } /// @@ -2211,7 +2272,7 @@ private void DecodeHeader(ScanMode scan) m = GetMarker(); while (m == 0xff) { - if (AtEof) + if (AtEnd()) throw Err("no SOF"); m = GetMarker(); } @@ -2239,7 +2300,7 @@ private void LoadTables() while (true) { int m = GetMarker(); - if (m == 0xd9 || (m == 0xff && AtEof)) + if (m == 0xd9 || (m == 0xff && AtEnd())) break; if (!ProcessMarker(m)) throw Err($"JPEG tables: bad or unsupported marker 0x{m:X2}"); @@ -2259,12 +2320,12 @@ private void LoadTables() /// private byte SkipJunkAtEnd() { - while (!AtEof) + while (!AtEnd()) { var x = Get8(); while (x == 0xff) { - if (AtEof) + if (AtEnd()) return 0xff; x = Get8(); if (x != 0x00 && x != 0xff) diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegImageDecoder.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegImageDecoder.cs index 1753aa1..cd637a7 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/JpegImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegImageDecoder.cs @@ -2,6 +2,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; +using System.Threading.Tasks; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -22,8 +23,16 @@ namespace Sdcb.SimdCodecs.Jpeg; /// smaller image at a fraction of the cost (); 16 and above decode at 1/8, then apply /// the box filter of for the rest. /// +/// +/// / read a JPEG from a forward-only stream a band of rows at a +/// time. A sequential frame whose first scan interleaves every component (every baseline file in practice) is decoded +/// as it arrives, holding about two MCU rows of samples and one MCU row of compressed bytes, at full size or at a +/// of 2, 4 or 8; progressive and multi-scan frames, regions, orientation +/// and larger scales read the whole stream first ( false). Either way the rows +/// are exactly 's. +/// /// -public sealed class JpegImageDecoder : IImageDecoder +public sealed class JpegImageDecoder : IStreamingImageDecoder { private static ReadOnlySpan Signature => [0xFF, 0xD8, 0xFF]; @@ -39,6 +48,7 @@ public sealed class JpegImageDecoder : IImageDecoder TryDecodeInto = TryDecodeInto, TryReadMetadata = TryReadMetadata, TryDecodeThumbnail = TryDecodeThumbnail, + CreateRowReader = CreateRowReader, }; /// @@ -209,6 +219,42 @@ public static bool TryReadMetadata(ReadOnlySpan data, [NotNullWhen(true)] public static bool TryDecodeThumbnail(ReadOnlySpan data, [NotNullWhen(true)] out IDecodedImage? thumbnail) => JpegMetadata.TryDecodeExifThumbnail(data, out thumbnail); + /// + public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) => + new JpegRowReader(input, format, options); + + /// + /// A reader of the JPEG in , from its current position, writing rows in + /// (see ). The header is read by the first read, or by + /// ; reads it asynchronously. + /// + /// The stream to read; it need not seek. + /// The layout of the rows to write. + /// Scale, region, orientation; null for the whole image at full size. + /// Keep open when the reader is disposed. + public static StreamingRowReader OpenRowReader(Stream stream, PixelFormat format, DecodeOptions? options = null, bool leaveOpen = false) => + CreateRowReader(new StreamInput(stream, leaveOpen), format, options); + + /// , then reads the header asynchronously. + /// + /// Cancels the header read. + /// The header is malformed or the stream ends inside it. + public static async ValueTask OpenRowReaderAsync(Stream stream, PixelFormat format, DecodeOptions? options = null, + bool leaveOpen = false, CancellationToken cancellationToken = default) + { + var reader = OpenRowReader(stream, format, options, leaveOpen); + try + { + await reader.InitializeAsync(cancellationToken).ConfigureAwait(false); + return reader; + } + catch + { + reader.Dispose(); + throw; + } + } + /// /// to tightly packed 8-bit RGBA: must be /// at least Width * Height * 4 bytes. diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegRowReader.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegRowReader.cs new file mode 100644 index 0000000..44095fa --- /dev/null +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegRowReader.cs @@ -0,0 +1,259 @@ +using System; +using System.Buffers; +using System.IO; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs.Jpeg; + +/// +/// The streaming JPEG reader (). A sequential frame whose first scan +/// interleaves every component — every baseline file in practice — is decoded as it arrives, MCU row by MCU row, holding +/// the engine's two-MCU-row strips and the compressed bytes of about one MCU row. Its rows are exactly +/// 's, at full size or a DCT-domain scale of 1/2, 1/4 or 1/8. Progressive +/// frames, frames split over several scans, frames with no scan, and the options it does not do on the fly (a region, +/// orientation, a scale past 1/8) take the buffered fallback. +/// +internal sealed class JpegRowReader : StreamingRowReader +{ + /// Rows decoded at a time when the output format is converted from the engine's. + private const int ConvertBand = 16; + + /// + /// The most rows one call writes. The driver checks its cancellation token between calls, and + /// the engine has none of its own here, so a large request over input that is all buffered is cut into calls of this + /// many rows: a call that stops at this limit reports NeedMoreData with rows written, which makes the driver check the + /// token and call again without reading. + /// + private const int YieldBand = 256; + + private readonly DecodeOptions? _options; + private JpegCore.Suspended? _core; + private int _headerMin; // the input length to wait for before trying the header again + private PixelFormat _coreFormat; // what the engine writes: Format, or Gray8 / Rgb24 converted to it + private byte[]? _band; // _coreFormat rows, when they are converted + private bool _failed; + + public JpegRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) + : base(input, format) + { + _options = options; + } + + 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; + if (!isFinal && input.Length < _headerMin) + return OperationStatus.NeedMoreData; + + // The header segments up to the first SOS, as JpegSegmentScanner reads them: the metadata in ImageInfo comes from + // them, so they must all be here before it is built (a cheap walk, before the engine parses anything). + var prefix = input.Length; + if (!isFinal) + { + switch (WalkHeader(input, out var end)) + { + case Walk.NeedMore: + _headerMin = Grow(input.Length); + return OperationStatus.NeedMoreData; + case Walk.Found: + prefix = end; + break; + } + } + + var scale = StreamingScale(_options); + var core = new JpegCore(input, scale == 0 ? 1 : scale); + var keep = false; + try + { + bool streams; + JpegInfo jpeg; + try + { + streams = core.StreamHeader(out jpeg); + } + catch (InvalidDataException) when (!isFinal && core.Overrun) + { + _headerMin = Grow(input.Length); + return OperationStatus.NeedMoreData; + } + + if (!isFinal && core.Overrun) + { + _headerMin = Grow(input.Length); + return OperationStatus.NeedMoreData; + } + + info = JpegImageDecoder.ToImageInfo(jpeg, input[..prefix]); + if (!streams || scale == 0) + { + UseBufferedFallback(JpegImageDecoder.TryDecodeInto, _options); + (width, height) = (_options ?? DecodeOptions.Default).GetOutputSize(info); + return OperationStatus.Done; + } + + _options?.Validate(info.Width, info.Height); + // The formats JPEG does not write natively are the decode's Gray8 / Rgb24 rows converted, as TryDecodeInto + // converts them. + _coreFormat = Format.IsBasic8 ? Format : jpeg.Components == 1 ? PixelFormat.Gray8 : PixelFormat.Rgb24; + core.BeginStreaming(JpegImageDecoder.ToJpegFormat(_coreFormat)); + (width, height) = (core.OutX, core.OutY); + if (!Format.IsBasic8) + _band = ArrayPool.Shared.Rent(checked(width * _coreFormat.BytesPerPixel * ConvertBand)); + consumed = core.Position; + _core = new JpegCore.Suspended(); + core.Suspend(_core, consumed); + keep = true; + return OperationStatus.Done; + } + finally + { + if (!keep) + core.ReturnBuffers(); + } + } + + protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed, + Span destination, int stride, int rowCount, out int rowsWritten) + { + if (_failed) + throw new InvalidDataException("JPEG: an earlier read of this stream failed."); + var suspended = _core ?? throw new InvalidOperationException("The header is not read."); + var core = new JpegCore(input, suspended); + var asked = rowCount; + rowCount = Math.Min(rowCount, YieldBand); + try + { + OperationStatus status; + if (_band is null) + { + status = core.StreamRows(isFinal, destination, stride, rowCount, out rowsWritten); + } + else + { + var width = Width; + var bandRow = width * _coreFormat.BytesPerPixel; + var outRow = width * Format.BytesPerPixel; + rowsWritten = 0; + do + { + status = core.StreamRows(isFinal, _band, bandRow, Math.Min(ConvertBand, rowCount - rowsWritten), out var got); + for (var i = 0; i < got; i++) + { + PixelConverter.ConvertRow(_band.AsSpan(i * bandRow, bandRow), _coreFormat, + destination.Slice((rowsWritten + i) * stride, outRow), Format, width); + } + + rowsWritten += got; + } while (status == OperationStatus.Done && rowsWritten < rowCount); + } + + consumed = core.Position; + core.Suspend(suspended, consumed); + return status == OperationStatus.Done && rowsWritten < asked ? OperationStatus.NeedMoreData : status; + } + catch + { + // The engine's state is part-way through a unit: nothing can resume from it. + _failed = true; + throw; + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (_core is { } suspended) + { + _core = null; + new JpegCore(default, suspended).ReturnBuffers(); + } + + if (_band is not null) + { + ArrayPool.Shared.Return(_band); + _band = null; + } + } + + base.Dispose(disposing); + } + + /// The DCT-domain scale the streaming decode runs at for ; 0 when they need the + /// buffered fallback. + private static int StreamingScale(DecodeOptions? options) + { + if (options is null) + return 1; + if (options.ApplyOrientation || options.Region is not null) + return 0; + return options.ScaleDenominator is 1 or 2 or 4 or 8 ? options.ScaleDenominator : 0; + } + + private static int Grow(int length) => (int)Math.Min(Array.MaxLength, length + (long)length / 4 + 1); + + private enum Walk + { + NeedMore, + Found, + Irregular, + } + + /// + /// 's walk over the header segments: with the end of the + /// first SOS segment (or of an EOI before it); where the scanner would run off the end + /// of ; where it would throw whatever followed. + /// + private static Walk WalkHeader(ReadOnlySpan jpeg, out int end) + { + end = 0; + if (jpeg.Length < 2) + return jpeg.Length == 0 || jpeg[0] == 0xFF ? Walk.NeedMore : Walk.Irregular; + if (jpeg[0] != 0xFF || jpeg[1] != 0xD8) + return Walk.Irregular; + var pos = 2; + while (true) + { + if (pos >= jpeg.Length) + return Walk.NeedMore; + if (jpeg[pos] != 0xFF) + return Walk.Irregular; + while (pos + 1 < jpeg.Length && jpeg[pos + 1] == 0xFF) + pos++; + if (pos + 1 >= jpeg.Length) + return Walk.NeedMore; + var marker = jpeg[pos + 1]; + if (marker == 0xD8 || marker == 0xD9 || marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)) + { + if (marker == 0xD9) + { + end = pos + 2; + return Walk.Found; + } + + pos += 2; + continue; + } + + if (pos + 4 > jpeg.Length) + return Walk.NeedMore; + var length = (jpeg[pos + 2] << 8) | jpeg[pos + 3]; + if (length < 2) + return Walk.Irregular; + if (pos + 2 + length > jpeg.Length) + return Walk.NeedMore; + if (marker == JpegSegmentScanner.Sos) + { + end = pos + 2 + length; + return Walk.Found; + } + + pos += 2 + length; + } + } +} diff --git a/src/Sdcb.SimdCodecs.Jpeg/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Jpeg/PublicAPI.Unshipped.txt index 7dc5c58..54d88ba 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs.Jpeg/PublicAPI.Unshipped.txt @@ -1 +1,4 @@ #nullable enable +static Sdcb.SimdCodecs.Jpeg.JpegImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! +static Sdcb.SimdCodecs.Jpeg.JpegImageDecoder.OpenRowReader(System.IO.Stream! stream, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, bool leaveOpen = false) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! +static Sdcb.SimdCodecs.Jpeg.JpegImageDecoder.OpenRowReaderAsync(System.IO.Stream! stream, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, bool leaveOpen = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/Sdcb.SimdCodecs.Jpeg/README.md b/src/Sdcb.SimdCodecs.Jpeg/README.md index 0c15dad..ed73cbb 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/README.md +++ b/src/Sdcb.SimdCodecs.Jpeg/README.md @@ -24,6 +24,20 @@ Scaled decode (`JpegScale.Half` and below) runs a reduced inverse DCT so neither JpegDecoder.DecodeTo(data, rgba, JpegScale.Quarter); ``` +Decode from a forward-only stream (a request body, a socket) a band of rows at a time: + +```csharp +using Sdcb.SimdCodecs.Abstractions; + +await using var reader = await JpegImageDecoder.OpenRowReaderAsync(stream, PixelFormat.Rgb24); +var band = new byte[reader.Width * 3 * 16]; +int rows; +while ((rows = await reader.ReadRowsAsync(band, 16)) > 0) + Consume(band, rows); +``` + +A sequential frame whose first scan interleaves every component (every baseline file in practice) is decoded as it arrives: the reader holds two MCU rows of samples per component and about one MCU row of compressed input, never the whole file or image, and reads the stream no further than the rows asked for need. It also scales in the DCT domain (`DecodeOptions.ScaleDenominator` 2, 4 or 8) on the fly. Progressive and multi-scan frames, regions, `ApplyOrientation` and larger scales read the whole stream and decode it first (`IsStreaming` is then false). Either way the rows are exactly `JpegImageDecoder.TryDecodeInto`'s for the same bytes, a truncated stream fails exactly where `TryDecodeInto` fails (and decodes the same salvaged pixels where it succeeds), and undecodable input throws `InvalidDataException`. `ReadRows` reads synchronously, `ReadRowsAsync` asynchronously; a reader may mix them. + Encode to a baseline JPEG: ```csharp diff --git a/tests/Sdcb.SimdCodecs.Tests/JpegDecoderOracleTests.cs b/tests/Sdcb.SimdCodecs.Tests/JpegDecoderOracleTests.cs index 6f34a7a..0333c15 100644 --- a/tests/Sdcb.SimdCodecs.Tests/JpegDecoderOracleTests.cs +++ b/tests/Sdcb.SimdCodecs.Tests/JpegDecoderOracleTests.cs @@ -222,7 +222,7 @@ byte[] Enc(TestJpegWriter.Component[] comps, Func sample, T public static IEnumerable CaseLabels() => OracleCases.Select(c => new object[] { c.Label }); - private static (byte[] Jpeg, JpegScale Scale) BuildCase(string label) + internal static (byte[] Jpeg, JpegScale Scale) BuildCase(string label) { var c = OracleCases.First(c => c.Label == label); return (c.Build(), c.Scale); diff --git a/tests/Sdcb.SimdCodecs.Tests/JpegFuzzTests.cs b/tests/Sdcb.SimdCodecs.Tests/JpegFuzzTests.cs index f1fe836..6e74c8d 100644 --- a/tests/Sdcb.SimdCodecs.Tests/JpegFuzzTests.cs +++ b/tests/Sdcb.SimdCodecs.Tests/JpegFuzzTests.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Jpeg; using Shouldly; @@ -103,6 +104,91 @@ public async Task MutatedStreams_DecodeOrThrowInvalidData() await work; } + private static int StreamIterations => + int.TryParse(Environment.GetEnvironmentVariable("JPEG_STREAM_FUZZ_ITERATIONS"), out var n) && n > 0 ? n + : int.TryParse(Environment.GetEnvironmentVariable("JPEG_FUZZ_ITERATIONS"), out n) && n > 0 ? n : 300; + + /// + /// The streaming reader () against the whole decode on the same damaged + /// streams: where succeeds the reader gives exactly its rows, fed in + /// random chunks (one byte at a time now and then) or async-only; where it fails the reader throws + /// — and nothing else, ever. Set JPEG_STREAM_FUZZ_ITERATIONS (or JPEG_FUZZ_ITERATIONS, which it follows when unset) for a soak. + /// + [Fact] + public async Task MutatedStreams_StreamingMatchesDecodeInto() + { + var seeds = Seeds.Value; + var iterations = StreamIterations; + var seed = Seed; + string? current = null; + var progress = 0; + var work = Task.Run(() => + { + var rng = new Random(seed ^ 0x5EED); + var scales = new[] { 1, 1, 1, 2, 4, 8 }; + var formats = new[] { PixelFormat.Rgba32, PixelFormat.Rgb24, PixelFormat.Gray8, PixelFormat.Bgra32, PixelFormat.Rgba64 }; + var feeds = new[] { Streaming.StreamingAssert.Feed.RandomChunks, Streaming.StreamingAssert.Feed.RandomChunks, Streaming.StreamingAssert.Feed.AsyncOnly, Streaming.StreamingAssert.Feed.OneByte }; + for (var it = 0; it < iterations; ++it) + { + var (name, original) = seeds[rng.Next(seeds.Length)]; + var how = "intact"; + var mutant = rng.Next(16) == 0 ? original : Mutate(original, rng, out how); + var scale = scales[rng.Next(scales.Length)]; + var format = formats[rng.Next(formats.Length)]; + var feed = feeds[rng.Next(feeds.Length)]; + current = $"iteration {it} (seed {seed}): {name}, {how}, 1/{scale}, {format}, {feed}"; + StreamOne(mutant, scale, format, feed, it, current); + Volatile.Write(ref progress, it + 1); + } + }, TestContext.Current.CancellationToken); + + var budget = TimeSpan.FromSeconds(Math.Max(60, iterations / 20)); + var finished = await Task.WhenAny(work, Task.Delay(budget, TestContext.Current.CancellationToken)); + (finished == work).ShouldBeTrue($"fuzz run did not finish in {budget} (stuck at {current}, {progress} done)"); + await work; + } + + private static void StreamOne(byte[] mutant, int scale, PixelFormat format, Streaming.StreamingAssert.Feed feed, int it, string context) + { + var options = scale == 1 ? null : new DecodeOptions { ScaleDenominator = scale }; + byte[]? expected = null; + if (JpegImageDecoder.TryReadInfo(mutant, out var info)) + { + var (w, h) = (options ?? DecodeOptions.Default).GetOutputSize(info); + if ((long)info.Width * info.Height > MaxPixels) + return; + var buffer = new byte[w * h * format.BytesPerPixel]; + if (JpegImageDecoder.TryDecodeInto(mutant, buffer, w * format.BytesPerPixel, format, options, CancellationToken.None)) + expected = buffer; + } + + var sw = Stopwatch.StartNew(); + byte[]? actual = null; + try + { + actual = Streaming.StreamingAssert.ReadAll(mutant, feed, input => JpegImageDecoder.CreateRowReader(input, format, options), + out _, out _, out _, seed: it + 1); + } + catch (InvalidDataException) + { + } + catch (Exception e) + { + throw new ShouldAssertException($"{context}: {e.GetType().Name}: {e.Message}", e); + } + + sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5), context); + if (expected is null) + { + actual.ShouldBeNull($"{context}: the whole decode rejects the stream, the reader accepted it"); + return; + } + + actual.ShouldNotBeNull($"{context}: the whole decode accepts the stream, the reader rejected it"); + if (!actual.AsSpan().SequenceEqual(expected)) + throw new ShouldAssertException($"{context}: rows differ from TryDecodeInto at byte {actual.AsSpan().CommonPrefixLength(expected)}"); + } + /// /// The Extended XMP joiner (JpegExtendedXmp) on damaged XML: the standard and extended packets are mutated /// as text (markup characters, truncation, deletion, duplication) and the GUID recomputed from the damaged bytes, diff --git a/tests/Sdcb.SimdCodecs.Tests/JpegStreamingDecodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/JpegStreamingDecodeTests.cs new file mode 100644 index 0000000..d63449f --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/JpegStreamingDecodeTests.cs @@ -0,0 +1,374 @@ +using System.Reflection; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Sdcb.SimdCodecs.Jpeg; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// The streaming JPEG reader: its rows are 's byte for byte, fed a stream every +/// way a network hands one over, at full size and at the DCT-domain scales; the variants it cannot stream fall back +/// transparently; a truncated stream fails where the whole decode fails; and its memory stays at about two MCU rows. +/// +public sealed class JpegStreamingDecodeTests +{ + private const long MaxPixels = 1 << 22; + + private static ImageDecoderRegistration Codec => JpegImageDecoder.Registration; + + private static DecodeOptions Scale(int denominator) => new() { ScaleDenominator = denominator }; + + private static readonly PixelFormat[] Formats = + [ + PixelFormat.Rgba32, PixelFormat.Bgra32, PixelFormat.Rgb24, PixelFormat.Bgr24, + PixelFormat.Gray8, PixelFormat.GrayAlpha16, PixelFormat.Rgba64, PixelFormat.Rgba32Premultiplied, + ]; + + public static IEnumerable Cases() => JpegDecoderOracleTests.CaseLabels(); + + /// Every case of the decode oracle matrix — every sampling, grayscale, CMYK / YCCK, restarts, non-interleaved, + /// the truncated salvage cases — through every feed and format, at full size and at 1/2. + [Theory] + [MemberData(nameof(Cases))] + public void Rows_EqualDecodeInto(string label) + { + var (jpeg, _) = JpegDecoderOracleTests.BuildCase(label); + if (!Codec.TryReadInfo(jpeg, out var info)) + return; // not decodable at all: nothing to compare + if ((long)info.Width * info.Height > MaxPixels) + return; + var streams = FirstScanInterleavesAll(jpeg); + foreach (var format in Formats) + { + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, null, streams); + if (streams) + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, Scale(2), true); + } + } + + /// The streaming rule, read independently: a sequential frame whose first SOS names every component. + private static bool FirstScanInterleavesAll(byte[] jpeg) + { + var info = JpegDecoder.ReadInfo(jpeg); + if (info.Progressive) + return false; + var segments = JpegSegmentScanner.Scan(jpeg); + var sos = segments[^1]; + return sos.Marker == JpegSegmentScanner.Sos && sos.Payload(jpeg)[0] == info.Components; + } + /// Encoded variants the encoder writes, restart intervals and optimized Huffman tables among them. + public static TheoryData EncodedShapes() => + [ + "4:2:0 restart 1", "4:2:0 restart 7", "4:4:4 optimized", "4:2:0 optimized restart 4", "gray restart 2", + "4:2:0 single mcu", "4:2:0 one row", "4:2:2 magick", "4:1:1 writer restart 2", + ]; + + [Theory] + [MemberData(nameof(EncodedShapes))] + public void EncodedVariants_StreamExactly(string shape) + { + var (w, h) = shape switch + { + "4:2:0 single mcu" => (16, 16), + "4:2:0 one row" => (67, 1), + _ => (67, 45), + }; + var jpeg = Encode(shape, w, h); + foreach (var format in Formats) + { + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, null, expectStreaming: true); + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, Scale(4), true); + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, Scale(8), true); + } + } + + private static byte[] Encode(string shape, int w, int h) + { + var rgb = JpegDecoderOracleTests.MakeRgbPattern(w, h); + if (shape.Contains("magick")) + return JpegDecoderOracleTests.EncodeJpeg(rgb, w, h, 75, "4:2:2"); + if (shape.Contains("writer")) + { + return TestJpegWriter.Encode(w, h, [new(1, 4, 1), new(2, 1, 1), new(3, 1, 1)], (k, x, y) => rgb[(y * w + x) * 3 + k], + new TestJpegWriter.Options { RestartInterval = 2 }); + } + + var restart = shape.Contains("restart ") ? int.Parse(shape[(shape.LastIndexOf(' ') + 1)..]) : 0; + var options = new JpegEncodeOptions + { + Quality = 85, + Subsampling = shape.StartsWith("4:2:0") ? JpegSubsampling.Chroma420 : JpegSubsampling.Chroma444, + RestartInterval = restart, + OptimizeHuffman = shape.Contains("optimized"), + }; + if (!shape.StartsWith("gray")) + return JpegEncoder.Encode(rgb, w, h, 3, options); + var gray = new byte[w * h]; + for (var i = 0; i < gray.Length; i++) + gray[i] = rgb[i * 3 + 1]; + return JpegEncoder.Encode(gray, w, h, 1, options); + } + /// + /// An Adobe APP14 or JFIF APP0 segment between SOF and SOS does not choose the colour transform in a whole decode (it + /// is chosen from the markers before SOF); the streaming reader, which reads up to SOS first, must not let it either. + /// + [Theory] + [InlineData(0xEE)] + [InlineData(0xE0)] + public void ColourSegmentAfterSof_IsIgnoredAsInTheWholeDecode(int marker) + { + var rgb = JpegDecoderOracleTests.MakeRgbPattern(37, 29); + var jpeg = TestJpegWriter.Encode(37, 29, [new(1, 1, 1), new(2, 1, 1), new(3, 1, 1)], (k, x, y) => rgb[(y * 37 + x) * 3 + k], + new TestJpegWriter.Options { AdobeTransform = 0, Jfif = marker == 0xE0 }); + var moved = MoveAfterSof(jpeg, (byte)marker); + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Gray8 }) + StreamingAssert.RowsEqualDecodeInto(Codec, moved, format, null, expectStreaming: true); + } + + /// with its first segment moved to just after SOF. + private static byte[] MoveAfterSof(byte[] jpeg, byte marker) + { + var segments = JpegSegmentScanner.Scan(jpeg); + var segment = segments.First(s => s.Marker == marker); + var sof = segments.First(s => s.Marker == 0xC0); + segment.SegmentOffset.ShouldBeLessThan(sof.SegmentOffset); + var bytes = jpeg.AsSpan(segment.SegmentOffset, segment.TotalLength).ToArray(); + var without = jpeg.Take(segment.SegmentOffset).Concat(jpeg.Skip(segment.SegmentOffset + segment.TotalLength)).ToList(); + without.InsertRange(sof.SegmentOffset - segment.TotalLength + sof.TotalLength, bytes); + return [.. without]; + } + + /// The variants that cannot stream say so and still give the whole decode's rows. + [Fact] + public void ProgressiveAndMultiScan_FallBack() + { + var rgb = JpegDecoderOracleTests.MakeRgbPattern(67, 45); + var progressive = JpegEncoder.Encode(rgb, 67, 45, 3, new JpegEncodeOptions { Quality = 80, Progressive = true }); + var luma = new byte[67 * 45]; + for (var i = 0; i < luma.Length; i++) + luma[i] = rgb[i * 3]; + var gray = JpegEncoder.Encode(luma, 67, 45, 1, new JpegEncodeOptions { Quality = 80, Progressive = true }); + var optimisedFinally = JpegDecoderOracleTests.EncodeJpeg(rgb, 67, 45, 75, "4:2:0"); + foreach (var jpeg in new[] { progressive, gray, optimisedFinally }) + { + var expect = jpeg == optimisedFinally; + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Gray8, PixelFormat.Rgb48 }) + { + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, null, expectStreaming: expect); + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, format, Scale(2), expect); + } + } + + // Options the streaming path does not honour on the fly take the fallback too, with the same rows. + var jpeg2 = JpegDecoderOracleTests.EncodeJpeg(rgb, 67, 45, 75, "4:2:0"); + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg2, PixelFormat.Rgba32, new DecodeOptions { Region = new PixelRect(5, 7, 20, 13) }, false); + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg2, PixelFormat.Rgba32, new DecodeOptions { ScaleDenominator = 16 }, false); + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg2, PixelFormat.Rgba32, new DecodeOptions { ApplyOrientation = true }, false); + } + + /// An Exif orientation is in from the header, and with orientation applied the reader + /// falls back and gives the displayed rows. + [Fact] + public void ExifOrientation_IsReportedAndApplied() + { + var rgb = JpegDecoderOracleTests.MakeRgbPattern(37, 29); + var jpeg = JpegEncoder.Encode(rgb, 37, 29, 3, new JpegEncodeOptions + { + Quality = 80, + Exif = MetadataTests.ExifBlock(orientation: 6), + }); + var info = JpegDecoder.ReadInfo(jpeg); + info.Orientation.ShouldNotBe(ImageOrientation.Normal); + + using var reader = JpegImageDecoder.OpenRowReader(new ChunkedStream(jpeg, 64), PixelFormat.Rgba32); + reader.Initialize(TestContext.Current.CancellationToken); + reader.Info.ShouldBe(JpegImageDecoder.Registration.TryReadInfo(jpeg, out var fresh) ? fresh : default); + reader.IsStreaming.ShouldBeTrue(); + + StreamingAssert.RowsEqualDecodeInto(Codec, jpeg, PixelFormat.Rgba32, new DecodeOptions { ApplyOrientation = true }, expectStreaming: false); + } + + /// Reading only the first rows reads only a prefix of the stream: the reader never asks for bytes the rows do + /// not need. + [Fact] + public void FirstRows_ReadOnlyAPrefix() + { + var rgb = JpegDecoderOracleTests.MakeRgbPattern(640, 480); + var jpeg = JpegEncoder.Encode(rgb, 640, 480, 3, new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Chroma420 }); + var stream = new ChunkedStream(jpeg, maxChunk: 4096); + using var reader = JpegImageDecoder.OpenRowReader(stream, PixelFormat.Rgba32); + reader.Initialize(TestContext.Current.CancellationToken); + var row = new byte[reader.Width * 4]; + reader.ReadRows(row, 1, 0, TestContext.Current.CancellationToken).ShouldBe(1); + stream.BytesRead.ShouldBeLessThan(jpeg.Length / 2, "the first row must not need the whole stream"); + } + + /// Truncating anywhere — inside every MCU row, in the markers after the scan — fails exactly where the whole + /// decode fails, and before then gives exactly its rows. + [Theory] + [InlineData("4:2:0 restart 0")] + [InlineData("4:2:0 restart 3")] + [InlineData("gray restart 0")] + [InlineData("4:4:4 restart 2")] + [InlineData("4:1:1 writer restart 2")] + public void Truncation_FailsWhereTheWholeDecodeFails(string shape) + { + var jpeg = Encode(shape, 31, 23); + var info = JpegDecoder.ReadInfo(jpeg); + var rowBytes = info.Width * 4; + var scratch = new byte[rowBytes * info.Height]; + var accepted = 0; + for (var cut = 0; cut <= jpeg.Length; cut++) + { + var truncated = jpeg.AsSpan(0, cut).ToArray(); + var context = $"{shape} cut at {cut} of {jpeg.Length}"; + if (Codec.TryDecodeInto(truncated, scratch, rowBytes, PixelFormat.Rgba32, null, TestContext.Current.CancellationToken)) + { + // Accepted (a missing EOI, a scan cut short): the reader gives exactly the salvaged rows. + StreamingAssert.RowsEqualDecodeInto(Codec, truncated, PixelFormat.Rgba32, null, null, + [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly]); + accepted++; + continue; + } + + foreach (var feed in new[] { StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.Whole }) + { + Should.Throw(() => StreamingAssert.ReadAll(truncated, feed, + input => JpegImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _, seed: cut + 1), + $"{context}, {feed}: the whole decode rejects it"); + } + } + + accepted.ShouldBeGreaterThan(0, "cuts inside the scan decode as salvage"); + } + /// Reading a 8000-row image band by band allocates far less than the image: the reader holds two MCU rows. + [Fact] + public void LargeImage_AllocatesBounded() + { + const int w = 5_000, h = 8_000; + var jpeg = TallJpeg(w, h); + var imageBytes = (long)w * h * 4; + var stream = new MemoryStream(jpeg, writable: false); + var band = new byte[16 * w * 4]; + + void Read() + { + stream.Position = 0; + using var reader = JpegImageDecoder.OpenRowReader(stream, PixelFormat.Rgba32, null, leaveOpen: true); + reader.Initialize(TestContext.Current.CancellationToken); + reader.IsStreaming.ShouldBeTrue(); + reader.Width.ShouldBe(w); + reader.Height.ShouldBe(h); + while (reader.RowsRead < h) + reader.ReadRows(band, 16).ShouldBeGreaterThan(0); + } + + StreamingAssert.AllocatesLessThan(imageBytes / 8, Read, "streaming a tall image"); + } + + /// A JPEG of × whose MCU rows are one-input-byte-like: a gradient at + /// high quality, so the file is small enough to build. + private static byte[] TallJpeg(int w, int h) + { + var rgb = new byte[w * h * 3]; + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) + { + var i = (y * w + x) * 3; + rgb[i] = (byte)(x >> 3); + rgb[i + 1] = (byte)(y >> 3); + rgb[i + 2] = (byte)((x ^ y) >> 4); + } + + return JpegEncoder.Encode(rgb, w, h, 3, new JpegEncodeOptions { Quality = 40, Subsampling = JpegSubsampling.Chroma420 }); + } + + /// End to end: a file read through an async-only stream, its rows equal the whole decode of its bytes. + [Fact] + public async Task FileStream_AsyncOnly() + { + var path = Path.Combine(Path.GetTempPath(), $"simdcodecs-stream-{Guid.NewGuid():N}.jpg"); + try + { + var rgb = JpegDecoderOracleTests.MakeRgbPattern(211, 137); + var jpeg = JpegEncoder.Encode(rgb, 211, 137, 3, new JpegEncodeOptions { Quality = 88 }); + File.WriteAllBytes(path, jpeg); + + var expected = new byte[211 * 137 * 4]; + Codec.TryDecodeInto(jpeg, expected, 211 * 4, PixelFormat.Rgba32, null, TestContext.Current.CancellationToken).ShouldBeTrue(); + + await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + var stream = new AsyncOnlyStream(file, maxChunk: 997); + await using var reader = await JpegImageDecoder.OpenRowReaderAsync(stream, PixelFormat.Rgba32, null, leaveOpen: true, + TestContext.Current.CancellationToken); + reader.IsStreaming.ShouldBeTrue(); + reader.Info.Width.ShouldBe(211); + var actual = new byte[expected.Length]; + while (reader.RowsRead < reader.Height) + { + var at = reader.RowsRead * 211 * 4; + (await reader.ReadRowsAsync(actual.AsMemory(at), 7, 0, TestContext.Current.CancellationToken)).ShouldBeGreaterThan(0); + } + + actual.ShouldBe(expected); + stream.SyncReads.ShouldBe(0); + } + finally + { + File.Delete(path); + } + } + + /// Read-only fields the resuming constructor derives from the saved decoder state and scale. + private static readonly HashSet Derived = ["_order", "_huffDc", "_huffAc", "_dequant", "_comp", "_blockSize"]; + + /// The suspension mirrors the engine: every field of JpegCore that is not a span has a namesake in + /// JpegCore.Suspended, so a field added to the engine cannot silently go unsaved. + [Fact] + public void Suspension_MirrorsTheEngine() + { + var core = typeof(JpegDecoder).Assembly.GetType("Sdcb.SimdCodecs.Jpeg.JpegCore")!; + var suspended = core.GetNestedType("Suspended", BindingFlags.NonPublic | BindingFlags.Public)!; + var saved = suspended.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + .Select(f => f.Name).ToHashSet(); + var spans = core.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + .Where(f => f.FieldType.IsByRefLike || f.FieldType == typeof(ReadOnlySpan) || f.FieldType == typeof(Span)) + .Select(f => f.Name).ToHashSet(); + spans.ShouldContain("_data"); + var missing = core.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + .Select(f => f.Name.StartsWith('<') ? f.Name[1..f.Name.IndexOf('>')] : f.Name) // auto-property backing fields + .Where(name => !spans.Contains(name) && !saved.Contains(name) && !Derived.Contains(name)) + .ToArray(); + missing.ShouldBeEmpty("fields of JpegCore that JpegCore.Suspended does not save"); + } + + /// A forward-only view of a stream that refuses synchronous reads (as a request body does) and returns at + /// most maxChunk bytes per read. + private sealed class AsyncOnlyStream(Stream inner, int maxChunk) : Stream + { + public int SyncReads { get; private set; } + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) + { + SyncReads++; + throw new InvalidOperationException("Synchronous operations are disallowed."); + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + inner.ReadAsync(buffer[..Math.Min(buffer.Length, maxChunk)], cancellationToken); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } +} \ No newline at end of file From baf2e37c3ce7af0481533fce9af467635fa16752 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:46:09 +0800 Subject: [PATCH 2/2] Jpeg streaming: wait for 1.5x the last MCU row's bytes before starting the next A row started near the end of the buffered input is usually undone and decoded again; waiting for about one row's worth of input first avoids the wasted work. Co-Authored-By: Claude Opus 5.5 --- src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs | 12 ++++++++---- src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs index fa196ab..d01eb0a 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs @@ -95,6 +95,7 @@ internal void BeginStreaming(JpegPixelFormat format) _sZeroFill = false; _sTail = TailRows; _sMinInput = 0; + _sRowBytes = 0; } /// @@ -144,7 +145,9 @@ private OperationStatus StreamUntil(int target, bool isFinal) } else { - if (!isFinal && _data.Length - _pos < _sMinInput) + // Wait for half as much again as the last row took (and what an undone attempt asked for), so a row is + // rarely started only to be undone at the end of the input: rows of a photo vary, but not by that much. + if (!isFinal && _data.Length - _pos < Math.Max(_sMinInput, _sRowBytes + _sRowBytes / 2)) return OperationStatus.NeedMoreData; var cp = Checkpoint(); bool ended; @@ -165,6 +168,7 @@ private OperationStatus StreamUntil(int target, bool isFinal) } _sMinInput = 0; + _sRowBytes = _pos - cp.Pos; _sZeroFill = ended; } @@ -361,7 +365,7 @@ internal sealed class Suspended internal int _bitCnt; internal int _sNextMcu; internal bool _sZeroFill; - internal int _sTail, _sTailMarker, _sMinInput; + internal int _sTail, _sTailMarker, _sMinInput, _sRowBytes; } /// The engine suspended in , over : the input from the position it @@ -414,7 +418,7 @@ internal JpegCore(ReadOnlySpan data, Suspended s) _bitCnt = s._bitCnt; _sNextMcu = s._sNextMcu; _sZeroFill = s._sZeroFill; - (_sTail, _sTailMarker, _sMinInput) = (s._sTail, s._sTailMarker, s._sMinInput); + (_sTail, _sTailMarker, _sMinInput, _sRowBytes) = (s._sTail, s._sTailMarker, s._sMinInput, s._sRowBytes); } /// Saves the engine into , its position made relative to @@ -459,6 +463,6 @@ internal readonly void Suspend(Suspended s, int consumed) s._bitCnt = _bitCnt; s._sNextMcu = _sNextMcu; s._sZeroFill = _sZeroFill; - (s._sTail, s._sTailMarker, s._sMinInput) = (_sTail, _sTailMarker, _sMinInput); + (s._sTail, s._sTailMarker, s._sMinInput, s._sRowBytes) = (_sTail, _sTailMarker, _sMinInput, _sRowBytes); } } diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs index 33374ef..b4744d8 100644 --- a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs +++ b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs @@ -263,6 +263,7 @@ internal enum DecodeMode private int _sTail; // TailRows … TailDone private int _sTailMarker; private int _sMinInput; // after a unit was undone: the input it waits for before trying again + private int _sRowBytes; // compressed bytes the last MCU row took: the input to wait for before the next private byte[]? _winScratch; // one full output row, when the window drops columns private bool _isRgb; private bool _chroma16;