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..d01eb0a
--- /dev/null
+++ b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.Streaming.cs
@@ -0,0 +1,468 @@
+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;
+ _sRowBytes = 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
+ {
+ // 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;
+ 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;
+ _sRowBytes = _pos - cp.Pos;
+ _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, _sRowBytes;
+ }
+
+ /// 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, _sRowBytes) = (s._sTail, s._sTailMarker, s._sMinInput, s._sRowBytes);
+ }
+
+ /// 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, s._sRowBytes) = (_sTail, _sTailMarker, _sMinInput, _sRowBytes);
+ }
+}
diff --git a/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs b/src/Sdcb.SimdCodecs.Jpeg/JpegCore.cs
index 5476be6..b4744d8 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,17 @@ 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 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;
@@ -285,7 +296,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 +376,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 +402,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 +542,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 +665,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 +769,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 +795,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 +1679,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 +2273,7 @@ private void DecodeHeader(ScanMode scan)
m = GetMarker();
while (m == 0xff)
{
- if (AtEof)
+ if (AtEnd())
throw Err("no SOF");
m = GetMarker();
}
@@ -2239,7 +2301,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 +2321,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