From 068a6fede02a039ac79a7f563f5b9c372b9cfef6 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:30:39 +0800 Subject: [PATCH] Pnm: streaming row reader (P1-P7) and streaming encoder session PnmImageDecoder implements IStreamingImageDecoder. The header is scanned as it arrives (resumable, at most 1 MiB) and then parsed by PnmHeader.Read as from the whole file; raw rows decode once their bytes are buffered, through the same chunk kernels as TryDecodeInto; plain rasters are read token by token with the number / comment state carried across reads. Non-full options take the buffered fallback. Rows equal TryDecodeInto's, with the same acceptance (trailing data ignored, short rasters refused). PnmImageEncoder.Create now returns a StreamingEncoderSession for every option: the header at AddFrame, each band's raster as it is written; the bytes equal the whole-image encode for any split. Tests: PnmStreamingTests (every variant x PixelFormat x feed, Magick.NET files, truncations, malformed input, memory bounds, encoder bytes, emits-before-commit, async end to end) and PnmStreamingRobustnessTests (PNM_STREAM_FUZZ_ITERATIONS). QoiPnm benchmark: row reader and streaming session contestants. Co-Authored-By: Claude Opus 5.5 --- .../Bench.cs | 42 +- .../Infrastructure.cs | 4 + src/Sdcb.SimdCodecs.Pnm/PnmEncoder.cs | 93 ++- src/Sdcb.SimdCodecs.Pnm/PnmImageDecoder.cs | 30 +- src/Sdcb.SimdCodecs.Pnm/PnmImageEncoder.cs | 34 +- src/Sdcb.SimdCodecs.Pnm/PnmPixels.cs | 48 ++ src/Sdcb.SimdCodecs.Pnm/PnmRowReader.cs | 304 ++++++++++ .../PublicAPI.Unshipped.txt | 1 + src/Sdcb.SimdCodecs.Pnm/README.md | 6 + .../PnmStreamingTests.cs | 533 ++++++++++++++++++ 10 files changed, 1066 insertions(+), 29 deletions(-) create mode 100644 src/Sdcb.SimdCodecs.Pnm/PnmRowReader.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/PnmStreamingTests.cs diff --git a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs index 7e96c9a..71b8395 100644 --- a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs +++ b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using System.Text; using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; using Sdcb.SimdCodecs.Png.Benchmarks; using Sdcb.SimdCodecs.Pnm; using Sdcb.SimdCodecs.Qoi; @@ -166,6 +167,19 @@ public static Setup Decode(Case c) if (!rgba.AsSpan().SequenceEqual(expected)) throw new InvalidOperationException($"{c.Name}: current does not give the source back"); } setup.Contestants.Add(new(Names.Current, () => Ours(rgba))); + if (!c.Qoi) + { + // The streaming reader over the same bytes, 16 rows a call, into the same kind of buffer. + var rows = new byte[rgba.Length]; + void ReadRows() + { + using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(data, writable: false)), PixelFormat.Rgba32, null); + while (reader.ReadRows(rows.AsSpan(reader.RowsRead * w * 4), 16) > 0) { } + } + ReadRows(); + if (!rows.AsSpan().SequenceEqual(rgba)) throw new InvalidOperationException($"{c.Name}: the row reader differs from TryDecodeInto"); + setup.Contestants.Add(new(Names.PnmRows, ReadRows)); + } if (Baseline.CanDecode(c.Qoi)) { @@ -233,6 +247,30 @@ void Check(string name, byte[] output) toStream(); })); + if (!c.Qoi && c.Format != "pfm") + { + // The streaming session, 16 rows a call, into a reused writer: the bytes of the whole-image encode. + var sessionFormat = c.Format == "ppm16" ? PixelFormat.Rgb48 : format; + var writer = new System.Buffers.ArrayBufferWriter(ours.Length); + void Session() + { + writer.ResetWrittenCount(); + using var session = PnmImageEncoder.Create(writer, c.Format == "ppm16" ? null : c.PnmOptions); + var frame = session.AddFrame(w, h, sessionFormat); + var rowBytes = w * sessionFormat.BytesPerPixel; + for (var y = 0; y < h; y += 16) + { + var n = Math.Min(16, h - y); + frame.WriteRows(pixels.AsSpan(y * rowBytes, n * rowBytes), n); + } + session.Commit(); + } + Session(); + if (!writer.WrittenSpan.SequenceEqual(ours)) throw new InvalidOperationException($"{c.Name}: the streaming session's bytes differ from Encode's"); + setup.Sizes[Names.PnmSession] = writer.WrittenCount; + setup.Contestants.Add(new(Names.PnmSession, Session)); + } + if (c.Format is not ("pfm" or "ppm16") && Baseline.CanEncode(c.Qoi)) { Func baseline; @@ -295,8 +333,8 @@ public static string Run(bool decode, int rounds) } var names = decode - ? new[] { Names.Current, Names.Baseline, Names.ImageSharp } - : [Names.Current, Names.CurrentStream, Names.Baseline, Names.ImageSharp]; + ? new[] { Names.Current, Names.PnmRows, Names.Baseline, Names.ImageSharp } + : [Names.Current, Names.CurrentStream, Names.PnmSession, Names.Baseline, Names.ImageSharp]; var compare = decode ? Names.Current : Names.CurrentStream; var sb = new StringBuilder(); sb.AppendLine($"### {(decode ? "Decode" : "Encode")} (in-process medians of {rounds} interleaved rounds, ms)"); diff --git a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs index a655db4..0a865b8 100644 --- a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs +++ b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs @@ -65,11 +65,15 @@ internal static class Names public const string CurrentStream = "CurrentStream"; public const string Baseline = "Baseline"; public const string ImageSharp = "ImageSharp"; + public const string PnmRows = "PnmRows"; + public const string PnmSession = "PnmSession"; public static string Label(string name) => name switch { Current => "current", CurrentStream => "current → stream", + PnmRows => "PNM row reader", + PnmSession => "PNM streaming session", Baseline => "baseline", _ => name, }; diff --git a/src/Sdcb.SimdCodecs.Pnm/PnmEncoder.cs b/src/Sdcb.SimdCodecs.Pnm/PnmEncoder.cs index 4c31818..147f944 100644 --- a/src/Sdcb.SimdCodecs.Pnm/PnmEncoder.cs +++ b/src/Sdcb.SimdCodecs.Pnm/PnmEncoder.cs @@ -247,6 +247,11 @@ public static Input Of(ReadOnlySpan samples, int width, int height, int ch return new Input(samples, width, height, (int)rowStride, channels, sixteen, false, format); } + /// A band of rows in a native layout (), 8- or 16-bit, + /// bytes apart; the caller has checked the size and the buffer. + public static Input OfRows(ReadOnlySpan rows, int width, int rowCount, int stride, PixelFormat native) => + new(rows, width, rowCount, stride, native.Channels, native.Sample == SampleFormat.UInt16, false, native); + public ReadOnlySpan Row(int y) => Pixels.Slice(y * Stride, Width * Channels * (Sixteen ? 2 : 1)); } @@ -266,12 +271,15 @@ private readonly record struct Target(PnmFormat Format, int Channels, int MaxVal }; } - private static Target Plan(in Input input, PnmEncodeOptions? options) + private static Target Plan(in Input input, PnmEncodeOptions? options) => + Plan(input.Width, input.Height, input.Channels, input.Sixteen, options); + + private static Target Plan(int width, int height, int inputChannels, bool sixteen, PnmEncodeOptions? options) { options ??= new PnmEncodeOptions(); var format = options.Format switch { - PnmFormat.Auto => input.Channels switch { 1 => PnmFormat.Graymap, 3 => PnmFormat.Pixmap, _ => PnmFormat.Arbitrary }, + PnmFormat.Auto => inputChannels switch { 1 => PnmFormat.Graymap, 3 => PnmFormat.Pixmap, _ => PnmFormat.Arbitrary }, >= PnmFormat.PlainBitmap and <= PnmFormat.Arbitrary => options.Format, _ => throw new ArgumentException($"{options.Format} is not a PBM, PGM, PPM or PAM format; PFM is written by EncodePfm.", nameof(options)), }; @@ -279,12 +287,12 @@ private static Target Plan(in Input input, PnmEncodeOptions? options) { PnmFormat.PlainBitmap or PnmFormat.Bitmap or PnmFormat.PlainGraymap or PnmFormat.Graymap => 1, PnmFormat.PlainPixmap or PnmFormat.Pixmap => 3, - _ => input.Channels, + _ => inputChannels, }; - if (input.Sixteen && (channels != input.Channels || format is PnmFormat.PlainBitmap or PnmFormat.Bitmap)) - throw new ArgumentException($"16-bit input of {input.Channels} channels cannot be written as {format}.", nameof(options)); + if (sixteen && (channels != inputChannels || format is PnmFormat.PlainBitmap or PnmFormat.Bitmap)) + throw new ArgumentException($"16-bit input of {inputChannels} channels cannot be written as {format}.", nameof(options)); var maxValue = format is PnmFormat.PlainBitmap or PnmFormat.Bitmap ? 1 - : options.MaxValue == 0 ? (input.Sixteen ? 65535 : 255) + : options.MaxValue == 0 ? (sixteen ? 65535 : 255) : options.MaxValue; if (maxValue is < 1 or > 65535) throw new ArgumentException($"Maximum value {maxValue} is not 1..65535.", nameof(options)); @@ -296,13 +304,13 @@ private static Target Plan(in Input input, PnmEncodeOptions? options) var tupleType = options.TupleType ?? channels switch { 1 => "GRAYSCALE", 2 => "GRAYSCALE_ALPHA", 3 => "RGB", _ => "RGB_ALPHA" }; if (tupleType.Length == 0 || tupleType.Any(c => c is < ' ' or > '~')) throw new ArgumentException("The tuple type must be printable ASCII on one line.", nameof(options)); - header = $"P7\nWIDTH {input.Width}\nHEIGHT {input.Height}\nDEPTH {channels}\nMAXVAL {maxValue}\nTUPLTYPE {tupleType}\nENDHDR\n"; + header = $"P7\nWIDTH {width}\nHEIGHT {height}\nDEPTH {channels}\nMAXVAL {maxValue}\nTUPLTYPE {tupleType}\nENDHDR\n"; } else { header = maxValue == 1 && format is PnmFormat.PlainBitmap or PnmFormat.Bitmap - ? $"P{magic}\n{input.Width} {input.Height}\n" - : $"P{magic}\n{input.Width} {input.Height}\n{maxValue}\n"; + ? $"P{magic}\n{width} {height}\n" + : $"P{magic}\n{width} {height}\n{maxValue}\n"; } return new Target(format, channels, maxValue, Encoding.ASCII.GetBytes(header)); } @@ -343,6 +351,73 @@ private static void ToStream(in Input input, Target target, Stream output) private static void Write(in Input input, Target target, IBufferWriter output) { output.Write(target.Header); + WriteRaster(input, target, output); + } + + /// + /// Writes a file a band of rows at a time: the header at , then each band's raster as it arrives. + /// Every row of a Netpbm raster is written on its own (a plain raster starts each row on a new line), so the bytes + /// are those of the whole-image encode however the rows are split. + /// + internal sealed class RowWriter : IDisposable + { + private readonly Target _target; + private readonly int _width; + private readonly PixelFormat _format, _native; + private byte[]? _scratch; + + private RowWriter(Target target, int width, PixelFormat format, PixelFormat native) + { + _target = target; + _width = width; + _format = format; + _native = native; + } + + /// + /// Plans a × image of rows and writes its + /// header. The rows are encoded as 's channels at its depth, straight alpha, RGB order: the + /// layout the buffered encode converts its input to. + /// + /// The size or options do not fit. + public static RowWriter Begin(int width, int height, PixelFormat format, PnmEncodeOptions? options, IBufferWriter output) + { + CheckSize(width, height); + var native = PixelFormat.ForChannels(format.Channels, format.Sample); + var target = Plan(width, height, native.Channels, native.Sample == SampleFormat.UInt16, options); + output.Write(target.Header); + return new RowWriter(target, width, format, native); + } + + /// Encodes rows, bytes apart (the caller checked both). + public void Write(ReadOnlySpan rows, int rowCount, int stride, IBufferWriter output) + { + if (_format == _native) + { + WriteRaster(Input.OfRows(rows, _width, rowCount, stride, _native), _target, output); + return; + } + var inBytes = _width * _format.BytesPerPixel; + var nativeBytes = _width * _native.BytesPerPixel; + _scratch ??= ArrayPool.Shared.Rent(nativeBytes); + var row = _scratch.AsSpan(0, nativeBytes); + for (var y = 0; y < rowCount; y++) + { + PixelConverter.ConvertRow(rows.Slice(y * stride, inBytes), _format, row, _native, _width); + WriteRaster(Input.OfRows(row, _width, 1, nativeBytes, _native), _target, output); + } + } + + public void Dispose() + { + if (_scratch is not null) + ArrayPool.Shared.Return(_scratch); + _scratch = null; + } + } + + private static void WriteRaster(in Input input, Target target, IBufferWriter output) + { int width = input.Width, channels = target.Channels, max = target.MaxValue; if (IsVerbatim(input, target)) { diff --git a/src/Sdcb.SimdCodecs.Pnm/PnmImageDecoder.cs b/src/Sdcb.SimdCodecs.Pnm/PnmImageDecoder.cs index 4cfd399..bdaa6b7 100644 --- a/src/Sdcb.SimdCodecs.Pnm/PnmImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Pnm/PnmImageDecoder.cs @@ -10,8 +10,9 @@ namespace Sdcb.SimdCodecs.Pnm; /// into the Sdcb.SimdCodecs facade. An image decodes as 8-bit samples up to a maximum value of 255, /// 16-bit above. writes the caller's buffer directly. Malformed data makes the /// Try methods return false rather than throw. PFM has its own adapter, . +/// decodes from a forward-only stream a row at a time. /// -public sealed class PnmImageDecoder : IImageDecoder +public sealed class PnmImageDecoder : IStreamingImageDecoder { /// The registration for ImageCodecs.Register, built from this type's method groups. public static ImageDecoderRegistration Registration { get; } = new() @@ -25,8 +26,19 @@ public sealed class PnmImageDecoder : IImageDecoder TryDecodeInto = TryDecodeInto, TryReadMetadata = TryReadMetadata, TryDecodeThumbnail = TryDecodeThumbnail, + CreateRowReader = CreateRowReader, }; + /// + /// + /// Every P1 to P7 image streams: the header is read whole (at most 1 MiB, comments included; a longer one throws + /// ), then each raw row as soon as its bytes are there and each plain row token by + /// token, holding a row of input and of samples. Options other than the whole image at full size decode the whole + /// stream first ( false). PFM is not read here: see . + /// + public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) => + new PnmRowReader(input, format, options); + /// /// P1 to P7 and a whitespace byte. public static int SignatureLength => 3; @@ -154,13 +166,7 @@ public static bool TryReadInfo(ReadOnlySpan data, bool pfm, out ImageInfo { try { - var pnm = Read(data, pfm, out _); - info = new ImageInfo(pnm.Width, pnm.Height, pnm.Channels, pnm.SampleFormat) - { - Format = pfm ? ImageFormat.Pfm : ImageFormat.Pnm, - BitDepth = pfm ? 32 : 32 - BitOperations.LeadingZeroCount((uint)pnm.MaxValue), - ColorEncoding = pfm ? LinearFloat : ColorEncoding.AssumedSrgb, - }; + info = ToImageInfo(Read(data, pfm, out _), pfm); return true; } catch (InvalidDataException) @@ -170,6 +176,14 @@ public static bool TryReadInfo(ReadOnlySpan data, bool pfm, out ImageInfo } } + public static ImageInfo ToImageInfo(in PnmInfo pnm, bool pfm) => + new(pnm.Width, pnm.Height, pnm.Channels, pnm.SampleFormat) + { + Format = pfm ? ImageFormat.Pfm : ImageFormat.Pnm, + BitDepth = pfm ? 32 : 32 - BitOperations.LeadingZeroCount((uint)pnm.MaxValue), + ColorEncoding = pfm ? LinearFloat : ColorEncoding.AssumedSrgb, + }; + public static IDecodedImage Decode(ReadOnlySpan data, bool pfm, DecodeOptions? options, CancellationToken cancellationToken) { diff --git a/src/Sdcb.SimdCodecs.Pnm/PnmImageEncoder.cs b/src/Sdcb.SimdCodecs.Pnm/PnmImageEncoder.cs index d618fa6..f14c1ad 100644 --- a/src/Sdcb.SimdCodecs.Pnm/PnmImageEncoder.cs +++ b/src/Sdcb.SimdCodecs.Pnm/PnmImageEncoder.cs @@ -1,5 +1,4 @@ using System.Buffers; -using System.Collections.Generic; using System.Threading; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -9,7 +8,8 @@ namespace Sdcb.SimdCodecs.Pnm; /// /// for Netpbm: the encoder abstraction's adapter over . /// Netpbm stores 8- and 16-bit grey, grey + alpha, RGB, or RGBA, so keeps depth, -/// straight alpha, and RGB order. +/// straight alpha, and RGB order. Every session streams (): the header +/// reaches the writer at AddFrame and each band of rows as it is written. /// public sealed class PnmImageEncoder : IImageEncoder { @@ -40,18 +40,32 @@ public static IImageEncoderSession Create(IBufferWriter output, EncodeOpti _ => throw new ArgumentException($"Netpbm encoding takes PnmEncodeOptions, not {options.GetType().Name}.", nameof(options)), }); - private sealed class Session(IBufferWriter output, PnmEncodeOptions options) : BufferedEncoderSession(output) + // Every Netpbm option encodes row by row (a plain raster starts each row on a new line), so every session streams: + // the header at AddFrame, each band's raster as WriteRows hands it over. + private sealed class Session(IBufferWriter output, PnmEncodeOptions options) : StreamingEncoderSession(output) { + private PnmEncoder.RowWriter? _writer; + public override int MaxFrames => 1; - protected override void Encode(IReadOnlyList frames, CancellationToken cancellationToken) + protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) => + _writer = PnmEncoder.RowWriter.Begin(width, height, format, options, Output); + + protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - var frame = frames[0]; - var native = GetClosestInputFormat(frame.Format); - var pixels = frame.PixelsAs(native); - var file = PnmEncoder.Encode(pixels, frame.Width, frame.Height, native, options); - WriteOutput(file); + _writer!.Write(rows, rowCount, stride, Output); + } + + protected override void Finish(CancellationToken cancellationToken) { } + + protected override void Dispose(bool disposing) + { + if (disposing) + _writer?.Dispose(); + _writer = null; + base.Dispose(disposing); } } -} +} \ No newline at end of file diff --git a/src/Sdcb.SimdCodecs.Pnm/PnmPixels.cs b/src/Sdcb.SimdCodecs.Pnm/PnmPixels.cs index dea0a0f..71ea5b1 100644 --- a/src/Sdcb.SimdCodecs.Pnm/PnmPixels.cs +++ b/src/Sdcb.SimdCodecs.Pnm/PnmPixels.cs @@ -53,6 +53,45 @@ public static void DecodeTo(ReadOnlySpan data, in PnmInfo info, int offset } } + /// The scratch takes: a chunk of 16-bit RGBA. + public const int RowScratchBytes = Chunk * 8; + + /// + /// Decodes one raw raster row ( bytes of ) into as + /// , as or, for 16-bit samples into a 16-bit layout, the native decode + /// then a conversion would: a chunk of pixels at a time, through + /// (). + /// + public static void DecodeRawRow(ReadOnlySpan raw, in PnmInfo info, Span row, PixelFormat format, Span scratch) + { + int width = info.Width, channels = info.Channels, bpp = format.BytesPerPixel; + if (info.SampleFormat == SampleFormat.UInt16 && format.Sample == SampleFormat.UInt16) + { + var max = (uint)info.MaxValue; + for (var x = 0; x < width; x += Chunk) + { + var n = Math.Min(Chunk, width - x); + var count = n * channels; + var from = MemoryMarshal.Cast(raw.Slice(2 * x * channels, 2 * count)); + var to = MemoryMarshal.Cast(scratch[..(2 * count)]); + if (BitConverter.IsLittleEndian) BinaryPrimitives.ReverseEndianness(from, to); + else from.CopyTo(to); + if (max != 65535) + for (var i = 0; i < to.Length; i++) + to[i] = Scale16(to[i], max); + PixelConverter.ConvertRow(scratch[..(2 * count)], channels, SampleFormat.UInt16, row[(x * bpp)..], format, n); + } + return; + } + scoped var source = new Source8(raw, info); + for (var x = 0; x < width; x += Chunk) + { + var n = Math.Min(Chunk, width - x); + var chunk = source.Read(0, x, n, scratch); + PixelConverter.ConvertRow(chunk, channels, SampleFormat.UInt8, row[(x * bpp)..], format, n); + } + } + /// Decodes to the native samples: , tightly packed. public static byte[] Decode(ReadOnlySpan data, in PnmInfo info, int offset) { @@ -179,6 +218,15 @@ private ref struct Source8 private int _plain; private readonly int _tier; + /// A raw raster's rows, from 's first byte (the streaming decoder: one row at a time). + public Source8(ReadOnlySpan raster, in PnmInfo info) + { + _info = info; + _rowBytes = RowBytes(info); + _tier = PnmKernels.BestTier; + _raster = raster; + } + public Source8(ReadOnlySpan data, in PnmInfo info, int offset) { _data = data; diff --git a/src/Sdcb.SimdCodecs.Pnm/PnmRowReader.cs b/src/Sdcb.SimdCodecs.Pnm/PnmRowReader.cs new file mode 100644 index 0000000..1fe9b91 --- /dev/null +++ b/src/Sdcb.SimdCodecs.Pnm/PnmRowReader.cs @@ -0,0 +1,304 @@ +using System.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs.Pnm; + +/// +/// The streaming decoder of P1 to P7 (). The header is scanned as it +/// arrives until its last field and terminator are there, then parsed by exactly as the +/// span decoder parses it. A raw row is decoded once all its bytes are buffered; a plain raster is read token by token +/// into a row of samples, its state (inside a number, inside a comment) carried across reads so that no token is split +/// and no comment is buffered. Rows equal 's: the same row decoders, and the +/// same acceptance (bytes after the last row are not read). +/// +internal sealed class PnmRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) : StreamingRowReader(input, format) +{ + /// The longest header read, comments included: it is buffered whole before it is parsed. + public const int MaxHeaderBytes = 1 << 20; + + private enum Scan { Space, Token, Keyword, FieldSpace, Digits, TupleLine, EndLine } + + // The header scan, resumed where the previous call stopped: each call sees the input from the first byte, with the + // bytes of the call before unchanged. + private int _scan = 2; + private Scan _state; + private bool _comment; + private int _tokens, _keywordStart, _digits; + + // The raster. + private PnmInfo _info; + private int _rowBytes; // a raw row's bytes + private bool _sixteen; // 16-bit samples into a 16-bit layout: rows are converted from native 16-bit samples + private byte[]? _scratch; // a raw row's chunk scratch, or a plain row's samples + + // A plain raster's position: the sample of the current row, and a number being read. + private int _sample; + private bool _inNumber; + private uint _value; + + protected override OperationStatus DecodeHeader(ReadOnlySpan input, bool isFinal, out int consumed, + out ImageInfo info, out int width, out int height) + { + consumed = width = height = 0; + info = default; + if ((input.Length > 0 && input[0] != 'P') + || (input.Length > 1 && input[1] is < (byte)'1' or > (byte)'7') + || (input.Length > 2 && !PnmHeader.IsSpace(input[2]))) + throw new InvalidDataException("Not a PBM, PGM, PPM or PAM image."); + if (!isFinal && (input.Length < 3 || !ScanHeader(input))) + { + if (_scan > MaxHeaderBytes) + throw new InvalidDataException($"The Netpbm header is longer than the {MaxHeaderBytes:N0} bytes a stream is read with."); + return OperationStatus.NeedMoreData; + } + + // The whole header is buffered: it parses as it does from the complete file. + var pnm = PnmHeader.Read(input, out var offset, tupleType: false); + info = PnmAdapter.ToImageInfo(pnm, pfm: false); + (width, height) = (pnm.Width, pnm.Height); + if (!IsFullImage(options)) + (width, height) = (options ?? DecodeOptions.Default).GetOutputSize(info); + if ((long)width * Format.BytesPerPixel > Array.MaxLength) + throw new InvalidDataException($"A {width}-pixel {Format} row does not fit in one buffer."); + if (!IsFullImage(options)) + { + UseBufferedFallback(PnmImageDecoder.TryDecodeInto, options); + return OperationStatus.Done; + } + var rowBytes = PnmPixels.RowBytes(pnm); + if (rowBytes > Array.MaxLength) + throw new InvalidDataException($"A {pnm.Width}-pixel Netpbm row does not fit in one buffer."); + _info = pnm; + _rowBytes = (int)rowBytes; + _sixteen = pnm.SampleFormat == SampleFormat.UInt16 && Format.Sample == SampleFormat.UInt16; + consumed = offset; + return OperationStatus.Done; + } + + // True once the bytes scanned hold the header's last field and the byte after it (P1 to P6), or the newline after + // ENDHDR (PAM); or once they hold something PnmHeader.Read rejects whatever follows (it then says why). Mirrors the + // fields PnmHeader.Read takes: decimal tokens after whitespace and '#' comments, PAM keyword lines. + private bool ScanHeader(ReadOnlySpan input) + { + var pam = input[1] == '7'; + var fields = input[1] is (byte)'1' or (byte)'4' ? 2 : 3; + var p = _scan; + try + { + while (p < input.Length) + { + var b = input[p]; + switch (_state) + { + case Scan.Space or Scan.FieldSpace: + if (_comment) + { + if (b is (byte)'\n' or (byte)'\r') _comment = false; + p++; + } + else if (PnmHeader.IsSpace(b)) p++; + else if (b == '#') { _comment = true; p++; } + else if (_state == Scan.FieldSpace) { _state = Scan.Digits; _digits = 0; } + else if (pam) { _state = Scan.Keyword; _keywordStart = p; } + else _state = Scan.Token; + break; + case Scan.Token: + if (IsDigit(b)) p++; + else if (PnmHeader.IsSpace(b) || b == '#') + { + if (++_tokens == fields) return true; + _state = Scan.Space; + } + else return true; + break; + case Scan.Keyword: + if (!PnmHeader.IsSpace(b)) + { + // The longest keyword is TUPLTYPE: anything longer is unknown. + if (p - _keywordStart >= 8) return true; + p++; + break; + } + var keyword = input[_keywordStart..p]; + if (keyword.SequenceEqual("ENDHDR"u8)) _state = Scan.EndLine; + else if (keyword.SequenceEqual("TUPLTYPE"u8)) _state = Scan.TupleLine; + else if (keyword.SequenceEqual("WIDTH"u8) || keyword.SequenceEqual("HEIGHT"u8) + || keyword.SequenceEqual("DEPTH"u8) || keyword.SequenceEqual("MAXVAL"u8)) _state = Scan.FieldSpace; + else return true; + break; + case Scan.Digits: + if (IsDigit(b)) { p++; _digits++; } + else if (_digits > 0 && (PnmHeader.IsSpace(b) || b == '#')) _state = Scan.Space; + else return true; + break; + case Scan.TupleLine: + if (b is (byte)'\n' or (byte)'\r') _state = Scan.Space; + else p++; + break; + default: // EndLine: whitespace to the newline + if (b == '\n' || !PnmHeader.IsSpace(b)) return true; + p++; + break; + } + } + return false; + } + finally + { + _scan = p; + } + } + + /// The scratch buffer's size (for tests). + internal int ScratchBytes => _scratch?.Length ?? 0; + + private static bool IsDigit(byte b) => b is >= (byte)'0' and <= (byte)'9'; + + protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed, + Span destination, int stride, int rowCount, out int rowsWritten) + { + consumed = rowsWritten = 0; + var outRowBytes = _info.Width * Format.BytesPerPixel; + if (!_info.IsPlain) + { + _scratch ??= ArrayPool.Shared.Rent(PnmPixels.RowScratchBytes); + var scratch = _scratch.AsSpan(0, PnmPixels.RowScratchBytes); + while (rowsWritten < rowCount) + { + if (input.Length - consumed < _rowBytes) + return OperationStatus.NeedMoreData; + PnmPixels.DecodeRawRow(input.Slice(consumed, _rowBytes), _info, destination.Slice(rowsWritten * stride, outRowBytes), + Format, scratch); + consumed += _rowBytes; + rowsWritten++; + } + return OperationStatus.Done; + } + + var samples = _info.Width * _info.Channels; + var p = 0; + while (rowsWritten < rowCount) + { + if (!ReadPlainRow(input, ref p, isFinal, samples)) + { + consumed = p; + return OperationStatus.NeedMoreData; + } + PixelConverter.ConvertRow(_scratch.AsSpan(0, samples * (_sixteen ? 2 : 1)), _info.Channels, + _sixteen ? SampleFormat.UInt16 : SampleFormat.UInt8, destination.Slice(rowsWritten * stride, outRowBytes), Format, _info.Width); + _sample = 0; + rowsWritten++; + } + consumed = p; + return OperationStatus.Done; + } + + // Reads the current plain row's samples from input[p..] into _scratch, as PnmPixels' plain readers do: a number ends + // at the first byte that is not a digit (or the stream's end), whitespace and comments separate. True once the row is + // complete; false when the input ends first, with every byte up to p taken into the state. + [MemberNotNull(nameof(_scratch))] + private bool ReadPlainRow(ReadOnlySpan input, ref int p, bool isFinal, int samples) + { + _scratch ??= ArrayPool.Shared.Rent(Math.Min(samples * (_sixteen ? 2 : 1), 4096)); + var bitmap = _info.Format == PnmFormat.PlainBitmap; + while (_sample < samples) + { + if (p == input.Length) + { + if (!isFinal) return false; + if (!_inNumber) throw new InvalidDataException("Netpbm raster is truncated."); + _inNumber = false; + Emit(_value, samples); + continue; + } + var b = input[p]; + if (_comment) + { + if (b is (byte)'\n' or (byte)'\r') _comment = false; + p++; + } + else if (_inNumber) + { + if (IsDigit(b)) + { + // Anything above 65535 is above every maximum and clamps alike. + _value = Math.Min(_value * 10 + (uint)(b - '0'), 65536); + p++; + } + else + { + _inNumber = false; + Emit(_value, samples); + } + } + else if (PnmHeader.IsSpace(b)) p++; + else if (b == '#') { _comment = true; p++; } + else if (bitmap) + { + Reserve(samples); + _scratch[_sample++] = b switch + { + (byte)'0' => 255, + (byte)'1' => 0, + _ => throw new InvalidDataException("PBM plain raster has a character other than 0 or 1."), + }; + p++; + } + else if (IsDigit(b)) + { + _inNumber = true; + _value = (uint)(b - '0'); + p++; + } + else + { + throw new InvalidDataException("Netpbm plain raster has a non-numeric sample."); + } + } + return true; + } + + // Makes room in _scratch for sample _sample. The scratch doubles as samples arrive (each takes at least one input + // byte), up to a row, so a header alone never makes it allocate a row. + [MemberNotNull(nameof(_scratch))] + private void Reserve(int samples) + { + var sampleBytes = _sixteen ? 2 : 1; + if (_scratch is not null && (_sample + 1) * sampleBytes <= _scratch.Length) return; + var grown = ArrayPool.Shared.Rent((int)Math.Min((long)samples * sampleBytes, Math.Max(4096L, 2L * (_scratch?.Length ?? 0)))); + if (_scratch is not null) + { + _scratch.AsSpan(0, _sample * sampleBytes).CopyTo(grown); + ArrayPool.Shared.Return(_scratch); + } + _scratch = grown; + } + + // One plain sample, scaled as PnmPixels scales it for this output. + private void Emit(uint value, int samples) + { + Reserve(samples); + var max = (uint)_info.MaxValue; + if (_sixteen) + MemoryMarshal.Cast(_scratch.AsSpan())[_sample++] = PnmPixels.Scale16(value, max); + else if (max > 255) + _scratch[_sample++] = (byte)(PnmPixels.Scale16(value, max) >> 8); + else if (max == 255) + _scratch[_sample++] = (byte)Math.Min(value, 255); + else + _scratch[_sample++] = PnmPixels.Scale8(value, max); + } + + protected override void Dispose(bool disposing) + { + if (disposing && _scratch is not null) + { + ArrayPool.Shared.Return(_scratch); + _scratch = null; + } + base.Dispose(disposing); + } +} diff --git a/src/Sdcb.SimdCodecs.Pnm/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Pnm/PublicAPI.Unshipped.txt index 7dc5c58..bbe3d09 100644 --- a/src/Sdcb.SimdCodecs.Pnm/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs.Pnm/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +static Sdcb.SimdCodecs.Pnm.PnmImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! diff --git a/src/Sdcb.SimdCodecs.Pnm/README.md b/src/Sdcb.SimdCodecs.Pnm/README.md index 548ff82..fd66dee 100644 --- a/src/Sdcb.SimdCodecs.Pnm/README.md +++ b/src/Sdcb.SimdCodecs.Pnm/README.md @@ -46,6 +46,12 @@ How the encoder converts the input to the chosen format: Plain output keeps every line within 70 characters and starts each image row on a new line. A PFM is written little-endian, which is scale −1, with its rows bottom-up as the format stores them. The layout, 16-bit and PFM overloads also have a `Stream` version that writes through one pooled buffer. +## Streaming + +`PnmImageDecoder.CreateRowReader` decodes P1 to P7 from a forward-only `Stream` (synchronously or asynchronously) a band of rows at a time, holding about a row of input and of samples. The rows are exactly those `TryDecodeInto` writes, and the reader accepts and refuses what it does: a short raster throws `InvalidDataException`, and bytes after the last row are never read. A raw row is decoded once all its bytes have arrived. A plain raster is read token by token, so a number or a comment may end anywhere in a read. The header, comments included, is buffered whole and may be at most 1 MiB in a stream. Options other than the whole image at full size read the whole stream first (`IsStreaming` false). PFM, with its bottom-up rows, has no streaming reader. + +`PnmImageEncoder.Create` always returns a streaming session: the header is written at `AddFrame`, and each band of rows as `WriteRows` hands it over. The bytes are the same as the whole-image encode, however the rows are split. + ## Decisions The format pages leave these cases open. The table shows what this package does: diff --git a/tests/Sdcb.SimdCodecs.Tests/PnmStreamingTests.cs b/tests/Sdcb.SimdCodecs.Tests/PnmStreamingTests.cs new file mode 100644 index 0000000..244ea33 --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/PnmStreamingTests.cs @@ -0,0 +1,533 @@ +using System.Buffers; +using System.Text; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Sdcb.SimdCodecs.Pnm; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; +using static Sdcb.SimdCodecs.Tests.Streaming.StreamingAssert; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// Netpbm from a forward-only stream () and into one +/// ('s streaming session): rows equal 's for +/// every P1 to P7 variant, depth and output layout under every feed; acceptance and rejection equal the span decoder's; +/// encoded bytes equal the whole-image encode however the rows are split, and reach the writer before Commit; memory +/// stays a few rows. +/// +public sealed class PnmStreamingTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private static ImageDecoderRegistration Codec => PnmImageDecoder.Registration; + + private static byte[] Ascii(string s) => Encoding.ASCII.GetBytes(s); + + private static byte[] Random8(int width, int height, int channels, int seed) + { + var pixels = new byte[width * height * channels]; + new Random(seed).NextBytes(pixels); + return pixels; + } + + /// Synthetic files of every format and depth our encoder writes. + public static IEnumerable<(string Name, byte[] File)> Synthetic(int width, int height) + { + var rgba = Random8(width, height, 4, width * 31 + height); + foreach (var format in new[] { PnmFormat.PlainBitmap, PnmFormat.PlainGraymap, PnmFormat.PlainPixmap, PnmFormat.Bitmap, PnmFormat.Graymap, PnmFormat.Pixmap, PnmFormat.Arbitrary }) + foreach (var max in new[] { 0, 7, 1000, 65535 }) + { + if (max != 0 && format is PnmFormat.Bitmap or PnmFormat.PlainBitmap) continue; + yield return ($"{format} max {max}", PnmEncoder.Encode(rgba, width, height, PixelFormat.Rgba32, new PnmEncodeOptions { Format = format, MaxValue = max })); + } + // 16-bit input: every sample value, not only 257 × v. + var wide = new ushort[width * height * 4]; + var random = new Random(width + 7 * height); + for (var i = 0; i < wide.Length; i++) wide[i] = (ushort)random.Next(65536); + foreach (var (format, channels) in new[] { (PnmFormat.Graymap, 1), (PnmFormat.Pixmap, 3), (PnmFormat.PlainGraymap, 1), (PnmFormat.PlainPixmap, 3), (PnmFormat.Arbitrary, 2), (PnmFormat.Arbitrary, 4) }) + foreach (var max in new[] { 0, 300, 4095 }) + yield return ($"{format} {channels}ch 16-bit max {max}", PnmEncoder.Encode(wide.AsSpan(0, width * height * channels), width, height, channels, new PnmEncodeOptions { Format = format, MaxValue = max })); + } + + /// Hand-written files: comments and odd whitespace everywhere, odd maxima, samples above the maximum, + /// trailing data and a second image, CR line ends, numbers with leading zeros, a raw row of 0x20 and 0x23 bytes. + public static IEnumerable<(string Name, byte[] File)> Hand() + { + yield return ("P1 comments", Ascii("P1\n# c1\n 3 # c2\n2\n1 0 1#x\n0#y\n1\r0 trailing")); + yield return ("P1 packed", Ascii("P1 5 2 1010101010")); + yield return ("P2 odd max", Ascii("P2 #a\r3\t2 # b\n 5 \n0 1 2\n3 4 9999999 ignored after")); + yield return ("P2 leading zeros", Ascii("P2\n2 2\n00000255\n0255 000 1 00\n")); + yield return ("P2 16-bit", Ascii("P2 2 2 1023 0 1023 512\n#mid\n70000")); + yield return ("P2 last sample at end", Ascii("P2 2 1 255 12 34")); + yield return ("P3 comments", Ascii("P3\n# header\n2 1\n# max\n255\n# raster\n255 0 0 # red\n0 0 255 # blue")); + yield return ("P4 bits", [.. Ascii("P4\n# c\n10 2\n"), 0b1010_1010, 0b1100_0000, 0b0101_0101, 0b0011_1111, 9, 9]); + yield return ("P5 space and hash raster", [.. Ascii("P5 4 2 255\n"), 0x20, 0x23, 0x0A, 0x30, 0x23, 0x20, 0x0D, 0x39]); + yield return ("P5 odd max", [.. Ascii("P5 3 1 100 "), 0, 50, 200]); + yield return ("P5 16-bit odd max", [.. Ascii("P5 2 1 1000\n"), 0x03, 0xE8, 0xFF, 0xFF]); + yield return ("P6 second image", [.. Ascii("P6 1 1 255\n"), 1, 2, 3, .. Ascii("P6 1 1 255\n"), 4, 5, 6]); + yield return ("P7 comments", [.. Ascii("P7\n# c\nWIDTH 2\n#d\nHEIGHT 1\nDEPTH 2 #e\nMAXVAL 255\nTUPLTYPE GRAYSCALE_ALPHA\nTUPLTYPE more\nENDHDR \n"), 1, 2, 3, 4]); + yield return ("P7 rgba 16", [.. Ascii("P7\nWIDTH 1\nHEIGHT 2\nDEPTH 4\nMAXVAL 65535\nENDHDR\n"), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); + yield return ("P5 long comment", [.. Ascii("P5\n#" + new string('x', 5000) + "\n2 1 255\n"), 7, 8]); + } + + private static PixelFormat[] AllFormats => PixelFormat.All.ToArray(); + + [Fact] + public void Small_synthetic_files_stream_to_the_rows_of_decode_into_every_feed_every_format() + { + foreach (var (name, file) in Synthetic(9, 5)) + foreach (var format in AllFormats) + Run(name, () => RowsEqualDecodeInto(Codec, file, format, expectStreaming: true), format); + } + + [Fact] + public void Hand_written_files_stream_to_the_rows_of_decode_into() + { + foreach (var (name, file) in Hand()) + foreach (var format in AllFormats) + Run(name, () => RowsEqualDecodeInto(Codec, file, format, expectStreaming: true), format); + } + + [Fact] + public void Wide_files_stream_across_chunks_of_a_row() + { + // 1100 pixels: past the 1024-pixel chunk, and a plain row longer than any read. + foreach (var (name, file) in Synthetic(1100, 3)) + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Gray8, PixelFormat.Rgb48, PixelFormat.Bgra64 }) + Run(name, () => RowsEqualDecodeInto(Codec, file, format, expectStreaming: true, feeds: [Feed.RandomChunks, Feed.AsyncOnly, Feed.Whole]), format); + } + + private static void Run(string name, Action check, PixelFormat format) + { + try + { + check(); + } + catch (Exception e) + { + throw new ShouldAssertException($"{name} into {format}: {e.Message}", e); + } + } + + [Fact] + public void Imagemagick_files_stream_as_the_span_decoder_reads_them() + { + var rgba = Random8(37, 6, 4, 5); + foreach (var (format, depth, plain, channels) in new[] + { + (MagickFormat.Pbm, 8u, false, 1), (MagickFormat.Pbm, 8u, true, 1), (MagickFormat.Pgm, 8u, false, 1), (MagickFormat.Pgm, 16u, true, 1), + (MagickFormat.Ppm, 8u, true, 3), (MagickFormat.Ppm, 16u, false, 3), (MagickFormat.Pam, 8u, false, 2), (MagickFormat.Pam, 16u, false, 4), + }) + { + using var image = new MagickImage(); + image.ReadPixels(rgba, new PixelReadSettings(37, 6, StorageType.Char, "RGBA")); + if (channels is 1 or 2) image.ColorType = channels == 1 ? ColorType.Grayscale : ColorType.GrayscaleAlpha; + if (channels is 1 or 3) image.Alpha(AlphaOption.Off); + image.Depth = depth; + if (plain) image.Settings.Compression = CompressionMethod.NoCompression; + var file = image.ToByteArray(format); + PnmDecoder.ReadInfo(file).IsPlain.ShouldBe(plain); + foreach (var target in new[] { PixelFormat.Rgba32, PixelFormat.Gray16, PixelFormat.Rgba64Premultiplied }) + Run($"{format} {depth} plain {plain}", () => RowsEqualDecodeInto(Codec, file, target, expectStreaming: true), target); + } + } + + [Fact] + public void Every_truncation_is_accepted_or_refused_as_the_span_decoder_does() + { + var files = Synthetic(5, 3).Concat(Hand().Where(h => h.File.Length < 400)).ToList(); + foreach (var (name, file) in files) + for (var length = 0; length <= file.Length; length++) + SameOutcome(file[..length], $"{name} cut to {length}", PixelFormat.Rgba32, seed: length); + } + + /// + /// Asserts the streaming reader does what the span decoder does with : the same rows, or + /// where is false. + /// + internal static void SameOutcome(byte[] data, string context, PixelFormat format, int seed) + { + byte[]? expected = null; + if (PnmImageDecoder.TryReadInfo(data, out var info) && (long)info.Width * info.Height <= 1 << 20) + { + var buffer = new byte[info.Width * info.Height * format.BytesPerPixel]; + if (PnmImageDecoder.TryDecodeInto(data, buffer, 0, format)) + expected = buffer; + } + else if (PnmImageDecoder.TryReadInfo(data, out _)) + { + return; // too large to decode here + } + foreach (var feed in new[] { Feed.RandomChunks, Feed.AsyncOnly, Feed.OneByte }) + { + byte[] actual; + try + { + actual = ReadAll(data, feed, input => PnmImageDecoder.CreateRowReader(input, format, null), out _, out _, out _, seed); + } + catch (InvalidDataException) + { + if (expected is not null) + throw new ShouldAssertException($"{context} ({feed}): the stream is refused but TryDecodeInto decodes it."); + continue; + } + catch (Exception e) + { + throw new ShouldAssertException($"{context} ({feed}): {e.GetType().Name}: {e.Message}", e); + } + if (expected is null) + throw new ShouldAssertException($"{context} ({feed}): the stream decodes but TryDecodeInto refuses it."); + if (!actual.AsSpan().SequenceEqual(expected)) + throw new ShouldAssertException($"{context} ({feed}): rows differ from TryDecodeInto."); + } + } + + [Fact] + public void A_short_raster_throws_invalid_data_from_read_rows() + { + var file = PnmEncoder.Encode(Random8(16, 8, 3, 1), 16, 8, 3); + using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(file[..^5], maxChunk: 50)), PixelFormat.Rgb24, null); + var rows = new byte[16 * 3 * 8]; + reader.ReadRows(rows, 7, 0, Ct).ShouldBe(7); + Should.Throw(() => reader.ReadRows(rows, 1, 0, Ct)); + } + + [Theory] + [InlineData("Pf 1 1 -1.0\n\0\0\0\0")] + [InlineData("P8 1 1 255\n\0")] + [InlineData("Q5 1 1 255\n\0")] + [InlineData("P5x1 1 255\n\0")] + [InlineData("P5 1 1 65536 \0\0")] + [InlineData("P5 1 1 255")] + [InlineData("P5 0 1 255 ")] + [InlineData("P5 1 1 255#\n\0")] + [InlineData("P7\nWIDTH 1\nHEIGHT 1\nDEPTH 5\nMAXVAL 255\nENDHDR\n\0")] + [InlineData("P7\nWIDTH 1\nHEIGHTS 1\nENDHDR\n\0")] + [InlineData("P7\nWIDTH 1\nHEIGHT 1\nDEPTH 1\nMAXVAL 255\nENDHDR x\n\0")] + [InlineData("P7\nWIDTH 1\nHEIGHT 1\nDEPTH 1\nMAXVAL 255\nENDHDR")] + [InlineData("P2 2 1 255 1 x")] + [InlineData("P1 2 1 1 2")] + public void Malformed_headers_and_rasters_throw_invalid_data(string text) + { + var file = Ascii(text); + PnmImageDecoder.TryDecodeInto(file, new byte[64], 0, PixelFormat.Rgba32, null, Ct).ShouldBeFalse(); + foreach (var feed in new[] { Feed.OneByte, Feed.AsyncOnly, Feed.Whole }) + Should.Throw(() => ReadAll(file, feed, input => PnmImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _)); + } + + [Fact] + public void A_row_too_wide_for_a_buffer_throws_invalid_data() + { + // 2^28 pixels of 8-byte RGBA64 is a 2 GiB row: not an OverflowException. + foreach (var feed in new[] { Feed.RandomChunks, Feed.Whole }) + Should.Throw(() => ReadAll(Ascii("P5 268435456 1 255\n\0"), feed, + input => PnmImageDecoder.CreateRowReader(input, PixelFormat.Rgba64, null), out _, out _, out _)); + } + + [Fact] + public void A_wide_plain_header_alone_allocates_no_row() + { + // The sample scratch grows with the samples that arrive, not with the width the header declares. + const int width = 1 << 24; + var file = Ascii($"P3 {width} 1 65535\n1 2 3 4"); + var row = new byte[width * 6]; + using var reader = (PnmRowReader)PnmImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(file)), PixelFormat.Rgb48, null); + Should.Throw(() => reader.ReadRows(row, 1, 0, Ct)); + reader.ScratchBytes.ShouldBeLessThanOrEqualTo(64 * 1024); + } + + [Fact] + public void A_header_past_the_streaming_limit_is_refused_after_reading_only_that_much() + { + var file = Ascii("P5\n#" + new string('x', 2 << 20) + "\n1 1 255\n\0"); + var stream = new ChunkedStream(file, maxChunk: 65536); + using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(stream), PixelFormat.Gray8, null); + Should.Throw(() => reader.Initialize(Ct)); + stream.BytesRead.ShouldBeLessThan((1 << 20) + 2 * 65536 + 1); + } + + [Fact] + public void A_long_comment_fed_a_byte_at_a_time_is_scanned_once() + { + // The header scan resumes where it stopped: 200 KB arriving a byte per read takes moments, not minutes. + var file = Ascii("P5\n#" + new string('x', 200_000) + "\n2 1 255\n\u0001\u0002"); + var watch = System.Diagnostics.Stopwatch.StartNew(); + ReadAll(file, Feed.OneByte, input => PnmImageDecoder.CreateRowReader(input, PixelFormat.Gray8, null), out _, out _, out _) + .ShouldBe(new byte[] { 1, 2 }); + watch.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10)); + } + + [Fact] + public void Options_other_than_the_full_image_take_the_buffered_fallback() + { + var file = PnmEncoder.Encode(Random8(40, 30, 3, 2), 40, 30, 3); + RowsEqualDecodeInto(Codec, file, PixelFormat.Rgba32, new DecodeOptions { Region = new PixelRect(3, 4, 20, 10) }, expectStreaming: false); + RowsEqualDecodeInto(Codec, file, PixelFormat.Rgb24, new DecodeOptions { ScaleDenominator = 2 }, expectStreaming: false); + RowsEqualDecodeInto(Codec, file, PixelFormat.Rgb24, new DecodeOptions(), expectStreaming: true); + } + + [Fact] + public void The_reader_reads_no_further_than_the_rows_asked_for() + { + var file = PnmEncoder.Encode(Random8(100, 100, 1, 3), 100, 100, 1); + var stream = new ChunkedStream(file, maxChunk: 1); + using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(stream, initialCapacity: 16), PixelFormat.Gray8, null); + var rows = new byte[100 * 10]; + reader.ReadRows(rows, 10, 0, Ct).ShouldBe(10); + stream.BytesRead.ShouldBe(file.Length - 90 * 100); + rows.ShouldBe(file.AsSpan(file.Length - 100 * 100, 1000).ToArray()); + } + + [Fact] + public void A_large_raw_image_streams_in_a_few_rows_of_memory() + { + // 8192 x 4096 grey (32 MiB) and RGB (96 MiB) read a row at a time. + foreach (var (channels, format) in new[] { (1, PixelFormat.Gray8), (3, PixelFormat.Rgba32) }) + { + const int width = 8192, height = 4096; + var header = Ascii($"P{(channels == 1 ? 5 : 6)}\n{width} {height}\n255\n"); + var file = new byte[header.Length + (long)width * height * channels]; + header.CopyTo(file, 0); + new Random(channels).NextBytes(file.AsSpan(header.Length, 1 << 16)); + var row = new byte[width * format.BytesPerPixel]; + AllocatesLessThan(256 * 1024, () => + { + using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(file, writable: false)), format, null); + while (reader.ReadRows(row, 1, 0, Ct) == 1) { } + reader.RowsRead.ShouldBe(height); + }, $"{channels} channels"); + } + } + + [Fact] + public void A_large_plain_image_streams_in_a_few_rows_of_memory() + { + const int width = 2048, height = 512; + var file = PnmEncoder.Encode(Random8(width, height, 3, 4), width, height, 3, new PnmEncodeOptions { Format = PnmFormat.PlainPixmap }); + var row = new byte[width * 4]; + AllocatesLessThan(256 * 1024, () => + { + using var reader = PnmImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(file, maxChunk: 4096)), PixelFormat.Rgba32, null); + while (reader.ReadRows(row, 1, 0, Ct) == 1) { } + }); + } + + // ---- the encoder ---------------------------------------------------------------------------------------------- + + public static IEnumerable EncoderOptions() + { + foreach (var format in new[] { PnmFormat.Auto, PnmFormat.PlainBitmap, PnmFormat.PlainGraymap, PnmFormat.PlainPixmap, PnmFormat.Bitmap, PnmFormat.Graymap, PnmFormat.Pixmap, PnmFormat.Arbitrary }) + foreach (var max in new[] { 0, 7, 1000 }) + { + if (max != 0 && format is PnmFormat.Bitmap or PnmFormat.PlainBitmap) continue; + yield return new PnmEncodeOptions { Format = format, MaxValue = max }; + } + yield return new PnmEncodeOptions { Format = PnmFormat.Arbitrary, TupleType = "CUSTOM" }; + } + + // What the session encoded before it streamed: the frame converted to the encoder's input layout, encoded whole. + private static byte[]? Buffered(byte[] pixels, int width, int height, PixelFormat format, PnmEncodeOptions options) + { + var native = PnmImageEncoder.GetClosestInputFormat(format); + try + { + return PnmEncoder.Encode(PixelConverter.ToPacked(pixels, 0, format, native, width, height), width, height, native, options); + } + catch (ArgumentException) + { + return null; // an option this input cannot be written with + } + } + + [Fact] + public void The_session_streams_the_bytes_of_the_whole_image_encode_for_any_bands() + { + const int width = 1037, height = 9; + var random = new Random(11); + foreach (var format in AllFormats) + { + var pixels = new byte[width * height * format.BytesPerPixel]; + random.NextBytes(pixels); + foreach (var options in EncoderOptions()) + { + var expected = Buffered(pixels, width, height, format, options); + var output = new ArrayBufferWriter(); + using var session = PnmImageEncoder.Create(output, options); + session.IsStreaming.ShouldBeTrue(); + if (expected is null) + { + Should.Throw(() => session.AddFrame(width, height, format), $"{format} {options}"); + continue; + } + var frame = session.AddFrame(width, height, format); + output.WrittenCount.ShouldBeGreaterThan(0, "the header is written at AddFrame"); + // Random bands with a stride wider than a row. + var rowBytes = width * format.BytesPerPixel; + var stride = rowBytes + 5; + var strided = new byte[stride * height]; + for (var y = 0; y < height; y++) pixels.AsSpan(y * rowBytes, rowBytes).CopyTo(strided.AsSpan(y * stride)); + var row = 0; + while (row < height) + { + var n = Math.Min(random.Next(1, 4), height - row); + frame.WriteRows(strided.AsSpan(row * stride), n, stride, Ct); + row += n; + } + session.Commit(Ct); + output.WrittenSpan.SequenceEqual(expected).ShouldBeTrue($"{format} {options}"); + } + } + } + + [Fact] + public void The_encoder_emits_before_commit() + { + var pixels = Random8(64, 32, 4, 6); + foreach (var options in EncoderOptions()) + { + var file = EncoderEmitsBeforeCommit(o => PnmImageEncoder.Create(o, options), pixels, 64, 32, PixelFormat.Rgba32); + file.ShouldBe(Buffered(pixels, 64, 32, PixelFormat.Rgba32, options), options.ToString()); + } + } + + private sealed class CountingWriter : IBufferWriter + { + private readonly byte[] _buffer = new byte[1 << 20]; + public long Count { get; private set; } + public void Advance(int count) => Count += count; + public Memory GetMemory(int sizeHint = 0) => _buffer; + public Span GetSpan(int sizeHint = 0) => _buffer; + } + + [Fact] + public void A_large_image_encodes_in_a_band_of_memory() + { + const int width = 8192, height = 4096; + var band = Random8(width, 16, 4, 7); + foreach (var options in new[] { new PnmEncodeOptions(), new PnmEncodeOptions { Format = PnmFormat.Pixmap, MaxValue = 1000 }, new PnmEncodeOptions { Format = PnmFormat.PlainGraymap } }) + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Bgra32 }) + { + var writer = new CountingWriter(); + AllocatesLessThan(256 * 1024, () => + { + using var session = PnmImageEncoder.Create(writer, options); + var frame = session.AddFrame(width, height, format); + for (var y = 0; y < height; y += 16) + frame.WriteRows(band, 16, 0, Ct); + session.Commit(Ct); + }, $"{options} {format}"); + writer.Count.ShouldBeGreaterThan((long)width * height / 2); + } + } + + // ---- end to end ----------------------------------------------------------------------------------------------- + + [Fact] + public async Task An_async_only_stream_decodes_and_reencodes_row_by_row_to_the_same_file() + { + foreach (var (name, file, format) in new[] + { + ("ppm", PnmEncoder.Encode(Random8(300, 41, 3, 8), 300, 41, 3), PixelFormat.Rgb24), + ("pgm 16", PnmEncoder.Encode(Enumerable.Range(0, 300 * 41).Select(i => (ushort)(i * 37)).ToArray(), 300, 41, 1), PixelFormat.Gray16), + ("plain ppm", PnmEncoder.Encode(Random8(300, 41, 3, 9), 300, 41, 3, new PnmEncodeOptions { Format = PnmFormat.PlainPixmap }), PixelFormat.Rgb24), + }) + { + var options = new PnmEncodeOptions { Format = PnmDecoder.ReadInfo(file).Format }; + var output = new ArrayBufferWriter(); + await using (var reader = PnmImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(file, maxChunk: 997, asyncOnly: true)), format, null)) + { + await reader.InitializeAsync(Ct); + using var session = PnmImageEncoder.Create(output, options); + var frame = session.AddFrame(reader.Width, reader.Height, format); + var band = new byte[reader.Width * format.BytesPerPixel * 7]; + int n; + while ((n = await reader.ReadRowsAsync(band, 7, 0, Ct)) > 0) + frame.WriteRows(band, n, 0, Ct); + session.Commit(Ct); + } + output.WrittenSpan.SequenceEqual(file).ShouldBeTrue(name); + RowsEqualDecodeInto(Codec, output.WrittenSpan.ToArray(), format, expectStreaming: true, feeds: [Feed.AsyncOnly]); + } + } +} + +/// +/// Hostile input for the streaming Netpbm reader: random mutations of seed files, read with random feeds, either give +/// exactly the span decoder's rows or throw where it refuses, within seconds. +/// PNM_STREAM_FUZZ_ITERATIONS (default 500) and PNM_STREAM_FUZZ_SEED set the soak. +/// +public sealed class PnmStreamingRobustnessTests +{ + private static int Iterations => + int.TryParse(Environment.GetEnvironmentVariable("PNM_STREAM_FUZZ_ITERATIONS"), out var n) ? n : 500; + + private static int Seed => + int.TryParse(Environment.GetEnvironmentVariable("PNM_STREAM_FUZZ_SEED"), out var n) ? n : 20261123; + + [Fact] + public async Task Mutations_stream_as_the_span_decoder_decodes_them() + { + var seeds = PnmStreamingTests.Synthetic(7, 3).Concat(PnmStreamingTests.Hand().Where(h => h.File.Length < 400)).ToList(); + var formats = new[] { PixelFormat.Rgba32, PixelFormat.Gray8, PixelFormat.Rgb48 }; + var iterations = Iterations; + var budget = TimeSpan.FromSeconds(Math.Max(60, iterations / 20)); + var current = ""; + var run = Task.Run(() => + { + var random = new Random(Seed); + for (var i = 0; i < iterations; i++) + { + var (name, seed) = seeds[random.Next(seeds.Count)]; + var data = Mutate(seed, random, out var description); + current = $"#{i} {name}: {description}"; + var timer = System.Diagnostics.Stopwatch.StartNew(); + PnmStreamingTests.SameOutcome(data, current, formats[random.Next(formats.Length)], i); + timer.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5), current); + } + }, TestContext.Current.CancellationToken); + if (await Task.WhenAny(run, Task.Delay(budget, TestContext.Current.CancellationToken)) != run) + throw new ShouldAssertException($"The fuzz loop is stuck at {current}"); + await run; + } + + private static byte[] Mutate(byte[] seed, Random random, out string description) + { + var data = seed.ToArray(); + var span = random.Next(2) == 0 ? Math.Min(64, data.Length) : data.Length; + var at = random.Next(Math.Max(1, span)); + switch (random.Next(7)) + { + case 0: + data[at] ^= (byte)(1 << random.Next(8)); + description = $"bit flip at {at}"; + break; + case 1: + data[at] = (byte)random.Next(256); + description = $"byte {at} = {data[at]}"; + break; + case 2: + data[at] = "0123456789 \n#9\r"u8[random.Next(15)]; + description = $"header character at {at}"; + break; + case 3: + { + var n = random.Next(2, 9); + for (var k = 0; k < n; k++) data[random.Next(data.Length)] ^= (byte)(1 << random.Next(8)); + description = $"{n} flips"; + break; + } + case 4: + description = $"cut to {at}"; + return data[..at]; + case 5: + description = $"bytes inserted at {at}"; + return [.. data[..at], .. "99 #c\n"u8, .. data[at..]]; + default: + var length = Math.Min(random.Next(1, 16), data.Length - at); + description = $"{length} bytes deleted at {at}"; + return [.. data[..at], .. data[(at + length)..]]; + } + return data; + } +}